<?php
/////////////////////////////
/// /new TPM专项 ti费用申请
/// ////////////////////////
namespace app\index\controller;
use phpDocumentor\Reflection\Types\Null_;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;
use PHPExcel;
use PHPExcel_Writer_Excel5;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Fill;
use PHPExcel_Style_Border;
use PHPExcel_Cell_DataType;

class Tifeiyong extends Commonti
{
    //主页面
    public function index($page=1,$list=20)
    {
        //获取类型列表

        $request = Request::instance();
        $data = $request->post();
        //dump($data);
       // $data = $request->get();
        //p($data);
        $eid=Session::get("employee_id");
        $where = "ap.type_id=3 and ap.cuser=$eid ";
        if ($data) {
            if ($data["no"])
                $where .= "and ap.sn={$data["no"]} ";
            if (trim($data["title"]))
                $where .= "and ap.title like '%{$data["title"]}%' ";
            if ($data["status"])
                $where .= "and ap.status={$data["status"]} ";
            if (trim($data["start"])) {
                $st = strtotime($data["start"]);
                $where .= "and ap.ctime>=$st ";
            }
            if (trim($data["end"])) {
                $ed = strtotime($data["end"]) + 24 * 3600;
                $where .= "and ap.ctime<$ed ";
            }

            if ($data["jxs"]){
                $where .= "and j.title like '%{$data["jxs"]}%' ";

                //$where .= "and j.title={$data["jxs"]} ";//jxs_id
            }

        } else {
            $data = ["no" => "", "title" => "", "status" => "", "start" => "", "end" => "","jxs" => ""];
        }
        $sum=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti_cate cc", "ap.cate_id=cc.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")

            ->join("cg_jxs j", "ap.jxs_id=j.id")
            ->where($where)->count();

        /**/



        $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;
        $applys = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti_cate cc", "ap.cate_id=cc.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")

            ->join("cg_jxs j", "ap.jxs_id=j.id")
            ->where($where)
            ->order("ap.ctime desc,ap.id desc")->limit($start,$list)
            ->field("ap.id,ap.sn,ap.title,ap.status,ap.status2,ec.em_name as cname,ap.ctime,ap.fb,ap.cate_id,ap.sfxyfk,j.title as jxs,ap.khtype,ap.is_ydqx")
            ->select();

        //p($applys); kefan
        for ($i = 0; $i < count($applys); $i++) {
            switch ($applys[$i]["status"]) {

                case 2:
                    $applys[$i]["status_type"] = "已打回";
                    break;
                case 3:
                    $applys[$i]["status_type"] = "区域领导审批";
                    break;
                case 4:
                    $applys[$i]["status_type"] = "拆分人审批";
                    break;
                case 5:
                    $applys[$i]["status_type"] = "集团领导审批";
                    break;
                case 6:
                    $applys[$i]["status_type"] = "抄送";
                    break;
                case 7:
                    $applys[$i]["status_type"] = "已归档";
                    break;
                case 8:
                    $applys[$i]["status_type"] = "已作废";
                    break;
                case 9:
                    $applys[$i]["status_type"] = "已否决";
                    break;
                default:
                    $applys[$i]["status_type"] = "草稿";
                    break;
            }
            $applys[$i]["ctime"] = date("Y-m-d", $applys[$i]["ctime"]);
            //echo $applys[$i]["id"];
            $fbnum = Db::table("cg_ti_list")->where(["ti_id" => $applys[$i]["id"], "hx_status" => 3])->count();
            //echo  Db::table("cg_ti_list")->getLastSql();die;
            //p($fbnum);
            if ($fbnum)
                $applys[$i]["kefan"] = 1;
            else
                $applys[$i]["kefan"] = 0;
            $henum = Db::table("cg_ti_list")->where(["ti_id" => $applys[$i]["id"], "hx_status" => 0])->count();
            if ($henum)
                $applys[$i]["kehe"] = 1;
            else
                $applys[$i]["kehe"] = 0;

            $yihenu = Db::table("cg_ti_hexiao_list")->where(["ti_id" => $applys[$i]["id"]])->count();
            if ($yihenu)
                $applys[$i]["yihe"] = 1;
            else
                $applys[$i]["yihe"] = 0;
        }
        $this->assign("applys", $applys);
//p($applys); // khtype
        $this->assign("data", $data);
        $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);

        return $this->fetch();
    }

    //主信息新增
    public function addInfoHtml(){
        $request = Request::instance();
        $aid = $request->get('aid');
        $from = $request->get('from');
        $from=$from?$from:1;
        $aid=$aid?$aid:0;
        $this->assign("from",$from);
        $fujian = [];
        if ($aid) {
            $apply = Db::table("cg_ti")->alias("ap")
                ->join("cg_jxs j", "ap.jxs_id=j.id")
                ->where(["ap.id" => $aid])->field("ap.id,ap.sn,ap.jxs_id,ap.is_notice,ap.brief as remark,ap.title,j.title as jxs,ap.attach as annex_id,status,is_jinhuo,jinhuo_jine,jinhuo_shijian_start,jinhuo_shijian_end")
                ->find();
            $apply['jinhuo_shijian_start']=date('Y-m-d',$apply['jinhuo_shijian_start']);
            $apply['jinhuo_shijian_end']=date('Y-m-d',$apply['jinhuo_shijian_end']);
            $this->assign("apply", $apply);
            //附件
            if ($apply["annex_id"])
                $fujian = Db::table("annex")->where("id in({$apply["annex_id"]})")->select();
            if($apply["status"]==2){
                $btn=$this->getbton(3,$aid);
                $this->assign("btn",$btn);
                $logs=$this->getlog($aid);
                //print_r($logs);
                $this->assign("logs",$logs);
            }

            $xxxx=Db::name('cg_ti_list')->where(['ti_id'=>$aid])->field('*')->select();//详细信息
            //dump($xxxx);die;  // yjfyl
            $xxxxnum=count($xxxx);

            foreach ($xxxx as $k2=>&$v2){
                if($xxxxnum!=0){
                    $v2['hdxl']=round($v2['yesSales']/$xxxxnum,2);
                }else{
                    $v2['hdxl']=$v2['yesSales'];
                }
                if(!empty($v2['hdxl'])){
                    $v2['yjfyl']=round(100*$v2['yjsjtrfy']/$v2['hdxl'],2).'%';
                }else{
                    $v2['yjfyl']=0;
                }

                $v2['sn']=$apply['sn'].'-'.$v2['sn'];
                $v2['title']=Db::name('cg_jxs')->where(['id'=>$v2['jxs_id']])->value('title');//经销商
                $v2['zxtime']=date('Y-m-d',$v2['start']).'至'.date('Y-m-d',$v2['end']);
                $v2['expCanTime']=date('Y-m-d',$v2['expCanTime']);
                $id2=$v2['cp_id'];
                switch ($v2['cp_type']){
                    case 0:
                        $id2=$v2['brand'];
                        $cp=Db::name('pro_brands')->where(['id'=>$id2])->field('brand_name name')->find();
                        $v2['cp_name']=$cp['name'];  // $v2['cp_name']
                        $v2['cp_type']='品牌';
                        break;
                    case 1:
                        $id2=$v2['category'];
                        $cp=Db::name('pro_category')->where(['id'=>$id2])->field('category_name name')->find();
                        $v2['cp_name']=$cp['name'];
                        $v2['cp_type']='品类';
                        break;
                    case 2:
                        $id2=$v2['series'];
                        $cp=Db::name('pro_series')->where(['id'=>$id2])->field('series_name name')->find();
                        $v2['cp_name']=$cp['name'];
                        $v2['cp_type']='系列';
                        break;
                    case 3:
                        $id2=$v2['sku'];
                        $cp=Db::name('pro_sku')->where(['id'=>$id2])->field('sku_name name')->find();
                        $v2['cp_name']=$cp['name'];
                        $v2['cp_type']='SKU';
                        break;
                    case 4:
                        $id2=$v2['product'];
                        $cp=Db::name('pro_products')->where(['id'=>$id2])->field('pro_name name')->find();
                        $v2['cp_name']=$cp['name'];
                        $v2['cp_type']='单品';
                        break;

                }

                $v2['feetype']=Db::name('cg_feiyongkemu3')->where(['id'=>$v2['feetype']])->value('title');//
                $v2['paymethod']=Db::name('cg_paymethod')->where(['id'=>$v2['paymethod']])->value('title');

                if(isset($v2['payeetype'])&&$v2['payeetype']==1){
                    $v2['payeetype']='经销商';
                    $v2['payee']=DB::name('cg_jxs')->where(['id'=>$v2['payee']])->value('title');

                }elseif (isset($v2['payeetype'])&&$v2['payeetype']==2){
                    $v2['payeetype']='供应商';
                    $v2['payee']=DB::name('gys')->where('id',$v2['payee'])->value('gys_name');
                }

                if(isset($v2['cl_type'])&&!empty($v2['cl_type'])){
                    $cl_type = [
                        ['title'=>'货架陈列','id'=>'1'],
                        ['title'=>'堆头陈列','id'=>'2'],
                        ['title'=>'端架陈列','id'=>'3'],
                        ['title'=>'包柱陈列','id'=>'4'],
                        ['title'=>'挂网陈列','id'=>'5'],
                        ['title'=>'其他陈列','id'=>'6'],
                    ];

                    foreach ($cl_type as $ck=>$cv){
                        if($v2['cl_type']==$cv['id']){
                            $v2['cl_type']=$cv['title'];
                        }
                    }
                }else{
                    $v2['cl_type']='';
                }

                if(isset($v2['cl_place'])&&!empty($v2['cl_place'])){
                    $cl_place = [
                        ['title'=>'主通道','id'=>'1'],
                        ['title'=>'副通道','id'=>'2'],
                        ['title'=>'收银台','id'=>'3'],
                        ['title'=>'卖场门口','id'=>'4'],
                        ['title'=>'端架两侧','id'=>'5'],
                        ['title'=>'其他位置','id'=>'6'],
                    ];

                    foreach ($cl_place as $ck=>$cv){
                        if($v2['cl_place']==$cv['id']){
                            $v2['cl_place']=$cv['title'];
                        }
                    }
                }else{
                    $v2['cl_place']='';
                }

                if(isset($v2['cl_size'])&&!empty($v2['cl_size'])){
                    $cl_size =[
                        ['title'=>'1m x 1m','id'=>'1'],
                        ['title'=>'2m x 1m','id'=>'2'],
                        ['title'=>'2m x 2m','id'=>'3'],
                        ['title'=>'4m x 1m','id'=>'4'],
                        ['title'=>'整节端架','id'=>'5'],
                        ['title'=>'半节端架','id'=>'6'],
                        ['title'=>'其他尺寸','id'=>'7'],
                    ];

                    foreach ($cl_size as $ck=>$cv){
                        if($v2['cl_size']==$cv['id']){
                            $v2['cl_size']=$cv['title'];
                        }
                    }
                }else{
                    $v2['cl_size']='';
                }

            }
            /*echo '456';
            dump($xxxx);die;
p($xxxx);  // yjfyl*/
            $this->assign("xxxx",$xxxx);
            $applynet = Db::table("cg_ti")->alias("ap")
                ->join("cg_ti_list apd", "apd.ti_id=ap.id")
                ->where("ap.id=$aid")
                ->field(" apd.ctime,ap.id,apd.start,apd.end,apd.brief,apd.cp_type,noSales,yesSales,feiyonglv,roi")
                ->group('apd.ctime')
                ->select();
            $feedate=['title'=>[],'hanshuis'=>[]];
            $all = ["hanshuis" => 0, "noSales" => 0, "yesSales" => 0, "feiyonglv" => 0, "hanshuis" => 0,"sellnums" => 0, "xiaoshoues" => 0, "buchas" => 0, "zonges" => 0,"jxscha"=>0,"netcha"=>0,"feiyonglv"=>0,"yujirois"=>0];
            //dump($applynet);die; //费用明细条数
            for ($i = 0; $i < count($applynet); $i++) {
                $applynet[$i]['daynum']=($applynet[$i]['end']-$applynet[$i]['start'])/(3600*24)+1;
                $applynet[$i]['start']=date('Y-m-d',$applynet[$i]['start']);
                $applynet[$i]['end']=date('Y-m-d',$applynet[$i]['end']);

                $id=$applynet[$i]['id'];
                $ctime=$applynet[$i]['ctime'];
                $cp_type=$applynet[$i]['cp_type'];
                switch ($cp_type){
                    case 0:
                        $cp_type='brand';
                        $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand as pro_name,category,series,sku,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids  from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                        $cptype='品牌';
                        $cp_name=array();
                        foreach ($a as $av=>$ak){
                            $cp=Db::name('pro_brands')->where(['id'=>$ak['pro_name']])->field('brand_name name')->find();
                            $cp_name[$av]=$cp['name'];
                        }
                        break;
                    case 1:
                        $cp_type='category';
                        $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category  as pro_name,series,sku,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids  from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                        $cptype='品类';
                        $cp_name=array();
                        foreach ($a as $av=>$ak){
                            $cp=Db::name('pro_category')->where(['id'=>$ak['pro_name']])->field('category_name name')->find();
                            $cp_name[$av]=$cp['name'];
                        }
                        break;
                    case 2:
                        $cp_type='series';
                        $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category,series  as pro_name,sku,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids  from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                        $cptype='系列';
                        $cp_name=array();
                        foreach ($a as $av=>$ak){
                            $cp=Db::name('pro_series')->where(['id'=>$ak['pro_name']])->field('series_name name')->find();
                            $cp_name[$av]=$cp['name'];
                        }
                        break;
                    case 3:
                        $cp_type='sku';
                        $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category,series,sku  as pro_name,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids  from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                        $cptype='SKU';
                        $cp_name=array();
                        foreach ($a as $av=>$ak){
                            $cp=Db::name('pro_sku')->where(['id'=>$ak['pro_name']])->field('sku_name name')->find();
                            $cp_name[$av]=$cp['name'];
                        }
                        break;
                    case 4:
                        $cp_type='product';
                        $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category,series,sku,product as pro_name,sum(net_id) as net_ids,sum(xt_id) as xt_ids   from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                        //$a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category,series,sku,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids  as pro_name  from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                        $cptype='单品';
                        $cp_name=array();
                        foreach ($a as $av=>$ak){
                            $cp=Db::name('pro_products')->where(['id'=>$ak['pro_name']])->field('pro_name name')->find();
                            $cp_name[$av]=$cp['name'];
                        }
                        break;
                }
                $applynet[$i]['cp_name']=$cp_name;
                $applynet[$i]['cp_type']=$cptype;
                $applynet[$i]['cp_num']=count($a);
                $kh='';
                //客户详情-系统
                if(isset($a[0]['xt_ids'])&&!empty($a[0]['xt_ids'])){
                    //$b = Db::table("cg_ti_list")->query("select xt_id,xt_zb,net_num  from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime   group by apd.xt_id ");
                    $b = Db::table("cg_ti_list")->query("select xt_id,xt_zb,net_num,sys.title  from  cg_ti_list as apd inner join cg_system as sys on apd.xt_id=sys.id where apd.ti_id=$id and apd.ctime=$ctime   group by apd.xt_id ");

                    foreach ($b as $bk=>$bv){
                        $kh.='<p>'.$bv['title'].'/'.$bv['net_num'].'家</p>';
                    }
                    $kh.='<p class="spanTotal">共<span>'.count($b).'</span>个系统</p>';

                }
                //客户详情-网点
                if(isset($a[0]['net_ids'])&&!empty($a[0]['net_ids'])){
                    $b = Db::table("cg_ti_list")->query("
                                select xt_zb,net_num,sys.title,count(net.id) as netnum,sys.id as sysid  
                                from  cg_ti_list as apd 
                                inner join cg_net as net on apd.net_id=net.id 
                                inner join cg_system as sys on net.system_id=sys.id 
                                where apd.ti_id=$id and apd.ctime=$ctime   
                                group by sys.id ");
                    foreach ($b as $bk=>&$bv){
                        $sysid=$bv['sysid'];
                        $sql="select apd.id
                                 from  cg_ti_list as apd 
                                 inner join cg_net as net on apd.net_id=net.id 
                                 inner join cg_system as sys on net.system_id=sys.id 
                                 where sys.id=$sysid and apd.ctime=$ctime  and apd.ti_id=$id
                                 group by net.id";
                        $c = Db::table("cg_ti_list")->query($sql);
                        $kh.='<p>'.$bv['title'].'/'.count($c).'家</p>';
                    }
                    $kh.='<p class="spanTotal">共<span>'.count($b).'</span>个系统</p>';
                }
                if(!empty($kh)){
                    $applynet[$i]['kh']=$kh;
                }else{
                    $applynet[$i]['kh']='-';////客户详情-经销商
                }

                //费用类型
                $sql="select apd.feetype,fy.title,apd.payee,apd.payeetype,apd.paymethod,pay.title as payname,apd.feiyongmiaoshu,apd.amount,apd.cl_type,apd.cl_place,apd.cl_size,sum(apd.hanshui) as hanshuis
                                 from  cg_ti_list as apd 
                                 inner join cg_feiyongkemu3 as fy on apd.feetype=fy.id
                                 inner join cg_paymethod as pay on apd.paymethod=pay.id  
                                 where  apd.ctime=$ctime  and apd.ti_id=$id
                                 group by apd.feetype";//anp

                $c = Db::table("cg_ti_list")->query($sql);
                $applynet[$i]['feenum']=count($c);
                $applynet[$i]['fee']=$c;
            }
            foreach ($applynet as $ak=>$av){
                foreach ($av['fee'] as $fk=>$fv){
                    $all["hanshuis"] += $fv["hanshuis"];
                    array_push($feedate['title'],$fv["title"]);
                    array_push($feedate['hanshuis'],$fv["hanshuis"]);
                }
                $all["noSales"] += $av["noSales"];
                $all["yesSales"] += $av["yesSales"];
            }
            if($all['yesSales']!=0){
                $all['feiyonglv'] = round(100*$all['hanshuis']/$all['yesSales'],2).'%';
            }
            $this->assign("applyde", $applynet);
        } else {
            $feedate=['title'=>[],'hanshuis'=>[]];
            $feeda=[];
           // $all = ["sellnums" => 0, "xiaoshoues" => 0, "buchas" => 0, "zonges" => 0, "hanshuis" => 0,"jxscha"=>0,"netcha"=>0,"feiyonglv"=>0,"yujirois"=>0];
            $all = ["hanshuis" => 0, "noSales" => 0, "yesSales" => 0, "feiyonglv" => 0, "hanshuis" => 0,"jxscha"=>0,"netcha"=>0,"feiyonglv"=>0,"yujirois"=>0];
            //$all = ["hanshuis" => 0, "xiaoshoues" => 0, "buchas" => 0, "zonges" => 0, "hanshuis" => 0,"sellnums" => 0, "xiaoshoues" => 0, "buchas" => 0, "zonges" => 0,"jxscha"=>0,"netcha"=>0,"feiyonglv"=>0,"yujirois"=>0];
            $apply=["id" => 0, "sn" => 0, "jxs_id" => 0, "is_notice" => 0,"remark" => 0, "title" => 0, "jxs" => 0, "annex_id" => 0, "status" => 0, "is_jinhuo" => 0, "jinhuo_jine" => 0, "jinhuo_shijian_start" => 0, "jinhuo_shijian_end" => 0];
            $this->assign("apply",$apply);
        }

        $hbxx=Db::name('cg_ti_hb')->where(['ti_id'=>$aid])->field('*')->select();
        $hbnum=count($hbxx);
        $this->assign('hbnum',$hbnum);
        $this->assign("hbxx",$hbxx);

//p($feedate);
        $feeda=[[]];
        foreach ($feedate['title'] as $fek=>$fev){
            $feeda[$fek]=['title'=>$fev,'hanshuis'=>$feedate['hanshuis'][$fek]];
        }
        if(empty($feeda[0])){
            $feeda=[];
        }
        //p($feeda);

        $this->assign("feeda",$feeda);
        //$all = ["hanshuis" => 0, "xiaoshoues" => 0, "buchas" => 0, "zonges" => 0, "hanshuis" => 0,"jxscha"=>0,"netcha"=>0,"feiyonglv"=>0,"yujirois"=>0];
        $this->assign("all", $all);
        $this->assign("aid", $aid);
        $this->assign("fujian", $fujian);

        return $this->fetch();
    }
    //添加费用明细Html
    public function addListHtml(){

        $request = Request::instance();
        $data = $request->get();
        $fylx='';
        $fylxnum=0;

        if(isset($data['formalhbl'])&&$data['formalhbl']=='on'){
            //die;
            $fylxnum++;
            if(empty($fylx)){
                $fylx='1';
            }
        }
        if(isset($data['tejiabucha'])&&$data['tejiabucha']=='on'){
            //die;
            $fylxnum++;
            if(empty($fylx)){
                $fylx='4';
            }else{
                $fylx='1,4';
            }
        }
        if(isset($data['wuliaolingy'])&&$data['wuliaolingy']=='on'){
            //die;
            $fylxnum++;
            if(empty($fylx)){
                $fylx='5';
            }else{
                $fylx.=',5';
            }
        }

        if(isset($data['suihuozhekou'])&&$data['suihuozhekou']=='on'){
            $fylx='2';
        }
        if(isset($data['projinchang'])&&$data['projinchang']=='on'){
            $fylx='7';
        }
        $this->assign('fylx',$fylx);
        //echo 'fylxnum:'.$fylxnum.',fylx:'.$fylx;die;
        $aid = $data["aid"];
        $this->assign("aid", $aid);
        //以上新加的

        $jxsid = $this->request->get('jxsid') ;
        if(empty($jxsid)||$jxsid='undefined'){
            $jxsid=Db::name('cg_ti')->where('id',$aid)->value('jxs_id');
        }
        $id = $this->request->get('id');
        $channeltype   = Db::name('cg_jxs')->where('id',$jxsid)->value('channeltype');
        //$fylx='fylx_1__channeltypes_6';
        $fylxs='fylx_'.$fylx.'__channeltypes_'.$channeltype;

        $this->assign('fylxs',$fylxs);
        $title   = Db::name('cg_jxs')->alias('jxs')
            ->join("cg_market_city cit","jxs.city=cit.id")
            ->join("cg_market_provice pro","cit.provice=pro.id")
            ->join("cg_market_zoning zon","pro.zoning=zon.id")
            ->where('jxs.id',$jxsid)->value('zon.title');
        $titlename   = Db::name('cg_jxs')->alias('jxs')
            ->where('jxs.id',$jxsid)->value('jxs.title');
        $this->assign('titlename',$titlename); //选择的经销商
        $this->assign('title',$title);//成本中心 之前选择的经销商所对应的地区

        $this->assign('jxsid',$jxsid);
        $this->assign('id',$id);
        $this->assign('channeltype',$channeltype);//ci

        //return $this->fetch('other/addfreemingxi');
        //echo'2';die;
        return $this->fetch();

    }
    //获取选定的经销商
    public function getjxs(){
        $data = $this->request->post();
    echo 'getjxs不完整';die;

    }
    public function getfylx()
    {

        $datapost = $this->request->post();
        $dataget = $this->request->get();
        if(isset($dataget['aid'])&&!empty($dataget['aid'])){
            $jxs_id=Db::name('cg_ti')->where('id', $dataget['aid'])->value('jxs_id');
        }else{
            $jxs_id=$datapost['jxs_id'];
        }
        //p($jxs_id);
        /*dump($datapost);
        dump($dataget);*/
        $num=$dataget['num'];
        $channeltype = Db::name('cg_jxs')->where('id', $jxs_id)->value('channeltype');

        $where = [];
        $where['freekmlx'] = ['EQ', $dataget['num']];
        $where['channeltypes'] = ['like', '%"' . $channeltype . '"%'];


        $data = Db::table('cg_feiyongkemu3')->order("id desc")->where($where)->field('title,id,pid')->select();
        $info = '';
        switch ($num){
            case 1:
                $info='常规后补类：';
                $tr='<tr class="for">';
                break;
            case 2:
                $info='随货折扣类：';
                $tr='<tr class="sui">';
                break;
            case 4:
                $info='特价补差类：';
                $tr='<tr class="tej">';
                break;
            case 5:
                $info='物料领用类：';
                $tr='<tr class="wul">';
                break;
            case 7:
                $info='产品进场类：';
                $tr='<tr class="pro">';
                break;
        }
        $len=count($data);
        for($i=0; $i<$len; $i++){
            if($i<($len-1)){
                $info.=$data[$i]['title'].',';
            }else{
                $info.=$data[$i]['title'];
            }
        }
        $data = $tr.'<td>'.$info.' </td></tr>';
        echo json_encode(['message'=>'ok','info'=>$data,'code'=>'200','redirect'=>'']);
    }



        //提交ti主信息
    public function saveInfo(){
        $data = $this->request->post();
        $valid['title'] = $data['title'];
        $valid['jxs_id'] = $data['jxs_id'];
        $this->Valid([
            'title|活动主题'  => 'require',
            'jxs_id|活动经销商'  => 'require',],$valid);

        $data = BiHaiChaoSheng::setData($data,['jinhuo_shijian_start','jinhuo_shijian_end','jinhuo_jine'],$data['is_jinhuo']);
        if($data['is_jinhuo']){
            $data['jinhuo_shijian_start'] = strtotime($data['jinhuo_shijian_start']);
            $data['jinhuo_shijian_end'] = strtotime($data['jinhuo_shijian_end']);
        }
        $insert = $data;
    // $this->Valid([],)
        $insert['cuser'] = $_SESSION['think']['employee_id'];
        $insert['ctime'] = time();
        $insert['puser'] = $_SESSION['think']['employee_id'];
        $insert['ptime'] = time();
        $TiApply2 = new TiApply2();
        $insert['sn'] = $TiApply2->produceSN();
        $insert['status'] = 1;
        //$insert['type_id'] = 0;
        $insert['type_id'] = 3;
//p($insert);
        $inId = Db::name('cg_ti')->insertGetId($insert);
        $retData['id'] = $inId;
        if($inId>0){
            echo json_encode(['message'=>'ok','value'=>$retData,'code'=>'200','redirect'=>'']);
        }else{
            echo json_encode(['message'=>'添加失败','code'=>'1010','redirect'=>'']);
        }

    }
    //suggest查找网点
    public function netjson2($jid)
    {
        $sys=db("cg_system_jxs")->where("jxs_id=$jid and isdel=0")->column("system_id");
        if($sys){
            $sys=implode(',',$sys);
            $data=db("cg_net")->where("system_id in ($sys)")->field("title,id")->select();
        }else{
            $data=[];
        }
        /*
        $data = Db::table('cg_net')->alias("n")
            ->join("cg_system s", "n.system_id=s.id")
            ->join("cg_jxs j", "s.jxs=j.id")
            ->where("j.id=$jid")
            ->field('n.title,n.id')->select();*/

        echo json_encode(['message' => 'ok', 'value' => $data, 'code' => '200', 'redirect' => '']);
    }

    //选择网点
    public function selectNet()
    {
        return $this->fetch();
    }

    //按照经销商返回网点树
    public function netTree()
    {
        $jid = $this->request->param('keyword');
        $where = [];
        $sys=db("cg_system_jxs")->where("jxs_id=$jid and isdel=0")->column("system_id");
        if($sys){
            $sys=implode(',',$sys);
            $data = db('cg_system')->where("id in ({$sys}) and isdel=0")
                ->field('id,title name')
                ->select();
            foreach ($data as $k => $v) {
                # code...
                $net=db("cg_net")->where("system_id={$v["id"]} and isdel=0")->field("id,title name")->select();
                $data[$k]['children'] = $net;
            }
        }else{
            $data=[];
        }

        echo json_encode($data);
    }

    //提交ti_list
    public function saveList(){
        $postData = $this->request->post();
        $postData['start'] = strtotime($postData['start']);
        $postData['end'] = strtotime($postData['end']);
        $postData['expCanTime'] = strtotime($postData['expCanTime']);
        $insert['cuser'] = $_SESSION['think']['employee_id'];
        $insert['ctime'] = time();
        $insert['start'] = $postData['start'];
        $insert['end'] = $postData['end'];
        $insert['expCanTime'] = $postData['expCanTime'];

        $insert = [];

        Db::name('cg_ti_list')->insertGetId($insert);
    }

    public function baocunapply()
    {
        $request = Request::instance();
        $data = $request->post();
        if ($data) {
            $yuanap=db("cg_ti")->where(["id"=>$data["aid"]])->find();
            if ($data["aid"])
                $dataup["id"] = $data["aid"];
            else
                return json_encode(["msg" => "至少要有一条明细！", "state" => 2]);
            $dataup["jxs_id"]=$yuanap["jxs_id"];
            if ($data["title"])
                $dataup["title"] = $data["title"];
            else
                return json_encode(["msg" => "主题不能为空", "state" => 2]);
            $dataup["attach"] = $data["fujian"];
            $dataup["is_notice"] = $data["is_notice"];
            $dataup["status"] = $data["state"];
            $dataup["ptime"] = time();
            $dataup["puser"] = Session::get("employee_id");
            if(isset($data["title"]))
                $dataup["title"] = $data["title"];

            if(isset($data["jinhuo_jine"]))
                $dataup["jinhuo_jine"] = $data["jinhuo_jine"];

            if(isset($data["jinhuo_shijian_start"]))
                $dataup["jinhuo_shijian_start"] = strtotime($data["jinhuo_shijian_start"]);
            if(isset($data["jinhuo_shijian_end"]))
                $dataup["jinhuo_shijian_end"] = strtotime($data["jinhuo_shijian_end"]);

            if(isset($data["is_jinhuo"]))
                $dataup["is_jinhuo"] = $data["is_jinhuo"];
            //p($data);

            Db::startTrans();
            try {
                $ys=$this->tiys($data["aid"]);
                if($ys===0&&$data['state']==3)
                    return json_encode(["msg" => "尚未设定ti预算格式无法提交", "state" => 2]);
                $res1 = Db::table("cg_ti")->update($dataup);

                //echo Db::table("cg_ti")->getLastSql();die;
                $savetype = $data['state'];
                if ($savetype == '3') {
                    if($ys){
                        Db::table("yusuan_detail")->insertAll($ys);
                    }
                    //此处id和本系统中流程id一致
                    $flowId = db('cg_workflowset')->where(['id' => '24'])->value('flow_id');

                    $data2 = [];
                    $data2['accessToken'] = session('accessToken');
                    $data2['flowId'] = $flowId;
                    $data2 = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf', $data2);
                    $insert = [];
                    $insert['ywlx'] = 24;
                    $row = db('cg_ti')->where('id', $data["aid"])->field('title,sn')->find();
                    $insert['rwmcjbh'] = $row['title'] . '[' . $row['sn'] . ']';
                    $insert['yw_id'] = $data["aid"];
                    $insert['status'] = 1;
                    $insert['department_id'] = db('department_employee')->where(['index' => 1, 'employee_id' => session('employee_id')])->value('department_id');
                    $insert['sqr_id'] = session('employee_id');
                    $insert['workId'] = $data2->workId;
                    $insert['trackId'] = $data2->flowNode->trackId;
                    db('cg_workflow')->insert($insert);
                }

            } catch (\Exception $e) {
                echo $e->getMessage();
                Db::rollBack();die;
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
            if ($res1) {

                Db::commit();

                return json_encode(["msg" => "", "state" => 1]);
            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
        } else {
            //echo 'rrrr';die;
            return json_encode(["msg" => "请正确提交", "state" => 2]);
        }
    } // 系统繁忙请稍后再试
 //"hx_status" => 3,
    public function addapply(){
        header("Content-type:text/html;charset=utf-8");
        $postData = $this->request->post();
        //p($postData);
        $fyl=$postData['yjfyl'];
        $fee=array(); //费用详情 的信息
        $feetype=array();//
        $jxsxt=array();
        $pp=array();
        $pl=array();
        $xl=array();
        $sku=array();
        $dp=array();

        $hbxx=array();

        if(!isset($postData['fRmb'])){
            return json_encode(["msg" => "至少有一条费用明细", "state" => "2"]);
        }

        foreach ($postData as $k=>&$v){
            /*$hbnum = substr_count($k, 'hbxx');
            if($hbnum){
                if (!$v){
                }else{
                    $hbfh=str_replace("hbxx","","$k");
                    $hbdata=explode(';',$v);
                    foreach ($hbdata as $hk=>$hv){
                        $hbv=explode(',',$hv);
                        foreach ($hbv as  $hk2=>$hv2){
                            $hbv=explode(':',$hv2);
                            $hbxdata[$hk][$hbv[0]]=$hbv[1];
                        }
                    }
//                    dump($hbxdata);
                    foreach ($hbxdata as $kk=>&$vv){
                        $vv['ti_id']=$postData['ti_id'];
                        if(isset($vv['wlName'])){
                            $wlName=$vv['wlName'];
                        }
                        $where = "m_type=2 and is_deleted=0 and is_actived=1 ";
                        $data = Db::table('pro_materials t')->field('t.material_name,t.id,unit,factory')->where($where)->select();
                        foreach ($data as $mk=>$mv){
                            if($mv['material_name']==$wlName){
                                $vv['unit']=$mv['unit'];
                                $vv['factory']=$mv['factory'];
                            }
                        }
                    }
                    //p($hbxdata);
                    foreach ($hbxdata as $hbkk=>$hbvv){
                        Db::table('cg_ti_hb')->insert($hbvv);
                    }

                }
                $nums=count($hbxx);
                array_push($hbxx,"$v");
            }*/
            $number = substr_count($k, 'feetype');
            if($number){
                if (!$v){
                    return json_encode(["msg" => "费用类型不能为空", "state" => "2"]);
                }
                $strings=str_replace("feetype","","$k");
                $nums=count($feetype);
                $feetypes[$strings]=$nums;  //处理其他参数时需要，比如处理收款方, $nums在处理收款方时当键值
                array_push($feetype,"$v");
            }
   //客户详情 系统
            $number2 = substr_count($k, 'JinXiaoShangNum');
            if(isset($postData['khxqtype'])&&$postData['khxqtype']==2&&$number2){
                if (!$v){
                    return json_encode(["msg" => "客户详情请正确填写", "state" => "2"]);
                }
                $strings2=str_replace("JinXiaoShangNum","","$k");
                $nums2=count($jxsxt);
                $jxstypes[$strings2]=$nums2;  //处理其他参数时需要，比如处理收款方, $nums在处理收款方时当键值
                array_push($jxsxt,"$v");//系统投放网点数
            }

            //处理产品详情 品牌 品类 系列 SKU 单品
//品牌
            $number3 = substr_count($k, 'proTableInput0');
            if($number3){
                $strings3=str_replace("proTableInput0","","$k");
                $nums3=count($pp);
                $pptypes[$strings3]=$nums3;  //处理其他参数时需要
                array_push($pp,"$v");
            }
//品类
            $number4 = substr_count($k, 'proTableInput1');
            if($number4){
                $strings4=str_replace("proTableInput1","","$k");
                $nums4=count($pl);
                $pltypes[$strings4]=$nums4;  //处理其他参数时需要
                array_push($pl,"$v");
            }
//系列
            $number5 = substr_count($k, 'proTableInput2');
            if($number5){
                $strings5=str_replace("proTableInput2","","$k");
                $nums5=count($xl);
                $xltypes[$strings5]=$nums5;  //处理其他参数时需要
                array_push($xl,"$v");
            }
//SKU
            $number6 = substr_count($k, 'proTableInput3');
            if($number6){
                $strings6=str_replace("proTableInput3","","$k");
                $nums6=count($sku);
                $skutypes[$strings6]=$nums6;  //处理其他参数时需要
                array_push($sku,"$v");
            }
//单品
            $number7 = substr_count($k, 'proTableInput4');
            if($number7){
                $strings7=str_replace("proTableInput4","","$k");
                $nums7=count($dp);
                $dptypes[$strings7]=$nums7;  //处理其他参数时需要
                array_push($dp,"$v");
            }
        }
        //p($dp);

        $postData['feetype']=$feetype;//费用类型
        $postData['jxsxt']=$jxsxt;//客户详情  系统
        $ppnum=0;
        $plnum=0;
        $xlnum=0;
        $skunum=0;
        $dpnum=0;
        $i=1;
        $j=1;
        $j2=1;
        $j3=1;
        $j4=1;

        if (!empty($pp)){
            $ppnum = count($pp);
            $i=0;
            foreach ($pp as $k=>$v){
                if(!empty($v)){
                    $i++;
                }
            }
        }
        if (!empty($pl)){
            $plnum = count($pl);
            $j=0;
            foreach ($pl as $k=>$v){
                if(!empty($v)){
                    $j++;
                }
            }
        }
        if (!empty($xl)){
            $xlnum = count($xl);
            $j2=0;
            foreach ($xl as $k=>$v){
                if(!empty($v)){
                    $j2++;
                }
            }
        }//$pl
        if (!empty($sku)){
            $skunum = count($sku);
            $j3=0;
            foreach ($sku as $k=>$v){
                if(!empty($v)){
                    $j3++;
                }
            }
        }//$pl
        if (!empty($dp)){
            $dpnum = count($dp);
            $j4=0;
            foreach ($dp as $k=>$v){
                if(!empty($v)){
                    $j4++;
                }
            }
        }
        $postData['jxsxttype']='';
        if($ppnum==$i){
            $postData['jxsxttype']=0;
            $cpxqtype=0;
            //把 品牌 产品数据拿过来
        }elseif($plnum==$j){
            $postData['jxsxttype']=1;
            $cpxqtype=1;
            $pptypes=$pltypes;
            $pp=$pl;
        }elseif($xlnum==$j2){
            $postData['jxsxttype']=2;
            $cpxqtype=2;
            $pptypes=$xltypes;
            $pp=$xl;
        }elseif($skunum==$j3){
            $postData['jxsxttype']=3;
            $cpxqtype=3;
            $pptypes=$skutypes;
            $pp=$sku;
        }elseif($dpnum==$j4){
            $postData['jxsxttype']=4;
            $cpxqtype=4;
            $pptypes=$dptypes;
            $pp=$dp;
        }
        $postData['pp']=$pp;//客户详情  系统
        $postData['cpzb']=array();
        //产品详情  品牌，品类，系列，SKU,单品
        $cpxq['type']=$cpxqtype;
        //p($postData);
        foreach ($pptypes as $k=>$v){
            $ppnum='proTableInputBl'.$cpxqtype.$k;
            if(isset($pptypes[$k])){ //需要换 （改变）
                $num=$pptypes[$k];
                if(isset($pp[$num])){
                    if($cpxq['type']!=4){
                        $postData['ppnum'][$num]=$postData[$ppnum];
                        $cpxq['ppnum'][$num]=$postData[$ppnum];
                    }else{
                        $postData['ppnum'][$num]=null;
                        $cpxq['ppnum'][$num]=null;
                    }
                }else{
                }
            }else{
            }
            //p($cpxq);
            $ppsm='proTableInputSm'.$cpxqtype.$k;
            if(isset($pptypes[$k])){
                $num2=$pptypes[$k];
                if(isset($pp[$num])){
                    $postData['ppsm'][$num2]=$postData[$ppsm];
                    $cpxq['ppsm'][$num2]=$postData[$ppsm];  //客户详情 系统名称
                }else{
                }
            }else{
            }
            if(isset($postData['fylx'])&&$postData['fylx']==2) {
                $nowprice = 'nowprice' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['nowprice'][$num2] = $postData[$nowprice];
                        $cpxq['nowprice'][$num2] = $postData[$nowprice];  //客户详情 系统名称
                    } else {
                    }
                }

                $oldprices = 'oldprices' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['oldprices'][$num2] = $postData[$oldprices];
                        $cpxq['oldprices'][$num2] = $postData[$oldprices];  //客户详情 系统名称
                    }
                }

                $dealerZheJiaLv = 'dealerZheJiaLv' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['ZheJiaLv'][$num2] = $postData[$dealerZheJiaLv];
                        $cpxq['ZheJiaLv'][$num2] = $postData[$dealerZheJiaLv];  //客户详情 系统名称
                    }
                }


                $cpnum = 'num' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['cpnum'][$num2] = $postData[$cpnum];
                        $cpxq['cpnum'][$num2] = $postData[$cpnum];  //客户详情 系统名称
                    }
                }
            }elseif (isset($postData['fylx'])&&$postData['fylx']==4) {
                $nowprice = 'nowprice' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['nowprice'][$num2] = $postData[$nowprice];
                        $cpxq['nowprice'][$num2] = $postData[$nowprice];  //客户详情 系统名称
                    } else {
                    }
                }
                $nowprice2 = 'nowprice2' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['nowprice2'][$num2] = $postData[$nowprice2];
                        $cpxq['nowprice2'][$num2] = $postData[$nowprice2];  //客户详情 系统名称
                    } else {
                    }
                }

                $oldprices = 'oldprices' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['oldprices'][$num2] = $postData[$oldprices];
                        $cpxq['oldprices'][$num2] = $postData[$oldprices];  //客户详情 系统名称
                    }
                }

                $oldprices2 = 'oldprices2' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['oldprices2'][$num2] = $postData[$oldprices2];
                        $cpxq['oldprices2'][$num2] = $postData[$oldprices2];  //客户详情 系统名称
                    }
                }

                $dealerZheJiaLv = 'dealerZheJiaLv' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['ZheJiaLv'][$num2] = $postData[$dealerZheJiaLv];
                        $cpxq['ZheJiaLv'][$num2] = $postData[$dealerZheJiaLv];  //客户详情 系统名称
                    }
                }

                $dealerZheJiaLv2 = 'dealerZheJiaLv2' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['ZheJiaLv2'][$num2] = $postData[$dealerZheJiaLv2];
                        $cpxq['ZheJiaLv2'][$num2] = $postData[$dealerZheJiaLv2];  //客户详情 系统名称
                    }
                }

                $yls = 'yls' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['yls'][$num2] = $postData[$yls];
                        $cpxq['yls'][$num2] = $postData[$yls];  //客户详情 系统名称
                    }
                }

                $hdls = 'hdls' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['hdls'][$num2] = $postData[$hdls];
                        $cpxq['hdls'][$num2] = $postData[$hdls];  //客户详情 系统名称
                    }
                }

                $cpnum = 'num' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['cpnum'][$num2] = $postData[$cpnum];
                        $cpxq['cpnum'][$num2] = $postData[$cpnum];  //客户详情 系统名称
                    }
                }

            }elseif (isset($postData['fylx'])&&$postData['fylx']==7){
                $lssghj = 'lssghj' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['lssghj'][$num2] = $postData[$lssghj];
                        $cpxq['lssghj'][$num2] = $postData[$lssghj];  //客户详情 系统名称
                    } else {
                    }
                }

                $mclsj = 'mclsj' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['mclsj'][$num2] = $postData[$mclsj];
                        $cpxq['mclsj'][$num2] = $postData[$mclsj];  //客户详情 系统名称
                    } else {
                    }
                }

            }
        }

        $cpxq['name']=$pp;
        if(isset($cpxq['type'])&&$cpxq['type']==4){
            if(isset($cpxq['name'])&&isset($cpxq['ppnum'])){
                $cpnum=count($cpxq['ppnum']);
                foreach ($cpxq['ppnum'] as $ppk=>&$ppv){
                    $ppv=round(100/$cpnum,2);
                }
            }
        }

        switch ($cpxq['type']){
            case 0:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_brands')->where(['id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    //$cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;
                }
                $cpxq['brand']=$cpxq['name'];
                break;
            case 1:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_category')->alias("cat")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    //$cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;
                }
                $cpxq['category']=$cpxq['name'];
                break;
            case 2:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_series')->alias("ser")
                        ->join("pro_category cat","ser.category_id=cat.id")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    //$cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;

                }
                $cpxq['series']=$cpxq['name'];
                break;
            case 3:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_sku')->alias("sku")
                        ->join("pro_series ser","sku.series_id=ser.id")
                        ->join("pro_category cat","ser.category_id=cat.id")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    //$cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;
                }
                $cpxq['sku']=$cpxq['name'];
                break;
            case 4:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_products')->alias("pro")
                        ->join("pro_sku sku","pro.sku_id=sku.id")
                        ->join("pro_series ser","sku.series_id=ser.id")
                        ->join("pro_category cat","ser.category_id=cat.id")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    //$cpxq['product'][$cpk]=null;
                }
                $cpxq['product']=$cpxq['name'];
                break;

        }
        //产品详情
        //echo '1';
        /*Db::startTrans();
        try {*/
        $postData['jxsxtname']=array();
        $postData['jxsxtnum']=array();
        if(isset($postData['khxqtype'])&&$postData['khxqtype']==2){
            foreach ($jxstypes as $k=>$v){
                $xtnum='JinXiaoShang'.$k;
                $payee=$k;
                if(isset($jxstypes[$k])){
                    $num=$jxstypes[$k];
                    if(isset($jxsxt[$num])){
                        $postData['jxsxt'][$num]=$postData[$xtnum];
                        $jxsnum['jxsxt'][$num]=$postData[$xtnum]; //客户详情 系统 网点数
                        $khxq['jxsxt'][$num]=$postData[$xtnum];
                    }else{
                    }

                }else{
                }
                $xtname='JinXiaoShangBl'.$k;
                $payee=$k;
                if(isset($jxstypes[$payee])){
                    $num=$jxstypes[$payee];
                    if(isset($jxsxt[$num])){
                        $postData['jxsxtname'][$num]=$postData[$xtname];
                        $jxsname['jxsxtzb'][$num]=$postData[$xtname];  //客户详情 系统名称
                        $khxq['jxsxtzb'][$num]=$postData[$xtname];
                    }else{
                    }

                }else{
                }
            }
            $khxq['jxsxtwetnum']=$jxsxt;
            foreach ($jxstypes as $k=>$v){
                $xtnum='JinXiaoShangNum'.$k;
                $payee=$k;
                if(isset($jxstypes[$k])){
                    $num=$jxstypes[$k];
                    if(isset($feetype[$num])){
                        $postData['jxsxtnum'][$num]=$postData[$xtnum];
                        $jxsnum['jxsxtnum'][$num]=$postData[$xtnum]; //客户详情 系统 网点数
                    }else{
                    }

                }else{
                }
//改为占比
                $xtname='JinXiaoShangBl'.$k;
                $payee=$k;
                if(isset($jxstypes[$payee])){
                    $num=$jxstypes[$payee];
                    if(isset($feetype[$num])){
                        $postData['jxsxtzb'][$num]=$postData[$xtname];
                        $jxsname['jxsxtzb'][$num]=$postData[$xtname];  //客户详情 系统名称
                    }else{
                    }

                }else{
                }
            }
        }
        /*} catch (\Exception $e) {
            Db::rollBack();echo $e->getMessage();die;
            return json_encode(["wrong" => "系统繁忙请稍后再试", "aid" => ""]);
        }*/
        /*
         * 费用类型处理
        */
        //未税总额
        if(isset($postData['fRmb']) && is_array($postData['fRmb'])){
            foreach ($postData['fRmb'] as $k1=>$v1){
                if (empty($v1)){
                    return json_encode(["msg" => "未税总额不能为空", "state" => "2"]);
                }
            }
        }
        //支付方式
        if(isset($postData['status']) && is_array($postData['status'])){
            foreach ($postData['status'] as $k1=>$v1){
                if (empty($v1)){
                    return json_encode(["msg" => "支付方式不能为空", "state" => "2"]);
                }
            }
        }
        $fee['feetype']=$feetype; //费用类型
        $fee['fRmb']=$postData['fRmb']; //未税总额
        $fee['status']=$postData['status'];//支付方式
        $fee['fbreif']=$postData['fbreif']; //费用说明

        $postData['payee']=array();

        foreach ($feetypes as $k=>$v){
            //收款方
            $payees='payee'.$k;
            $payee=$k;
            if(isset($feetypes[$payee])){
                $num=$feetypes[$payee];
                if(isset($feetype[$num])){
                    $postData['payee'][$num]=$postData[$payees];
                    $fee['payee'][$num]=$postData[$payees];
                }else{
                }

            }else{
            }

            // 货补信息 payees
            $hbxxs='hbxx'.$k;
            $payee=$k;
            $hbxdata=array();
            if(isset($feetypes[$payee])){
                $num=$feetypes[$payee];
                if(isset($feetype[$num])) {
                    $postData['hbxx'][$num] = $postData[$hbxxs];
                    $fee['hbxx'][$num] = $postData[$hbxxs];
                    try {
                    $hbdata = explode(';', $postData[$hbxxs]);
                    foreach ($hbdata as $hk => $hv) {
                        if(!empty($hv)){
                            $hbv = explode(',', $hv);
                            foreach ($hbv as $hk2 => $hv2) {
                                $hbv = explode(':', $hv2);
                                if(isset($hbv[1])){
                                    $hbxdata[$hk][$hbv[0]] = $hbv[1];
                                }
                            }
                        }
                    }
                    foreach ($hbxdata as $kk2 => &$vv2) {
                        if(isset($fee['feetype'][$v])){
                            $vv2['fylx']=$fee['feetype'][$v];
                        }else{
                            $vv2['fylx']='';
                        }
                        $vv2['fylx']=$fee['feetype'][$v];
                        $vv2['ti_id'] = $postData['ti_id'];
                        if (isset($vv2['wlName'])) {
                            $wlName = $vv2['wlName'];
                        }
                        $where = "m_type=2 and is_deleted=0 and is_actived=1 ";

                        if(isset($vv2['wlyptype'])&&$vv2['wlyptype']==1){ //物料
                            $data = Db::table('pro_materials t')->field('t.material_name,t.id,unit,factory')->where(['material_name'=>$vv2['wlName']])->find();
                            $vv2['unit'] = $data['unit'];
                            $vv2['factory'] = $data['factory'];
                        }else{ //样品
                            $data = Db::table('pro_products')->alias("p")
                                ->join("pro_price pp", "pp.pid=p.id")
                                ->field('p.pro_name,pp.factory,p.unit')->where(['p.pro_name'=>$vv2['wlName']])->find();
                            if(!empty($data)){
                                $vv2['unit'] = $data['unit'];
                                $vv2['factory'] = $data['factory'];
                            }
                        }
                    } // $kk  $vv


                } catch (\Exception $e) {
                        return $e->getMessage();die;
                        Db::rollBack();
                        return json_encode(["msg" => "系统繁忙请稍后再试1", "state" => "2"]);
                    }

                }else{
                }

            }

            $allhb[$v]=$hbxdata;
            foreach ($hbxdata as $hk=>$hv){
                $allhb2[]=$hv;
            }


            //陈列方式
            $cl_types='cl_type'.$k;
            $cl_type=$k;
            if(isset($feetypes[$cl_type])){

                $num=$feetypes[$cl_type];
                if(isset($feetype[$num])){
                    $postData['cl_type'][$num]=$postData[$cl_types];
                    if(!empty($postData[$cl_types])){
                        $fee['cl_type'][$num]=$postData[$cl_types];
                    }else{
                        $fee['cl_type'][$num]=Null;
                    }
                }
            }
            $cl_places='cl_place'.$k;
            $cl_place=$k;
            if(isset($feetypes[$cl_place])){
                $num=$feetypes[$cl_place];
                if(isset($feetype[$num])){
                    $postData['cl_place'][$num]=$postData[$cl_places];

                    if(!empty($postData[$cl_places])){
                        $fee['cl_place'][$num]=$postData[$cl_places];
                    }else{
                        $fee['cl_place'][$num]=Null;
                    }

                }

            }

            $cl_sizes='cl_size'.$k;
            $cl_size=$k;
            if(isset($feetypes[$cl_size])){
                $num=$feetypes[$cl_size];
                if(isset($feetype[$num])){
                    $postData['cl_size'][$num]=$postData[$cl_sizes];

                    if(!empty($postData[$cl_sizes])){
                        $fee['cl_size'][$num]=$postData[$cl_sizes];
                    }else{
                        $fee['cl_size'][$num]=Null;
                    }

                }
            }


//payee

            //成本中心
            $cbzx='cbzx'.$k;
            $payee=$k;
            if(isset($feetypes[$payee])){
                $num=$feetypes[$payee];
                if(isset($feetype[$num])){
                    //处理成本中心
                    if(isset($postData[$cbzx])&&!empty($postData[$cbzx])){

                    }else{
                        $postData[$cbzx]=$postData['zon'].',100%';
                    }

                    $fcbzx=explode(';',$postData[$cbzx]);
                    $fcb=array();
                    foreach ($fcbzx as $cbk=>$cbv){
                        $fcbzx2=explode(',',$cbv);
                        $fcb[$cbk]=$fcbzx2;
                    }
                    $fee['cbzx'][$num]=$fcb;
                }else{
                }
            }else{
            }

            //货补信息 hbxx

        }

        $abc=$allhb;
        $allhb22=$allhb;

        $fee['feetype']=$feetype;
        foreach ($postData['payee'] as $kk=>$vv){
            if (empty($vv)){
                return json_encode(["msg" => "供应商不能为空", "state" => "2"]);
            }elseif($vv<0){
                $postData['payeetype'][$kk]=1;//收款方是经销商
                $postData['payee'][$kk]=$postData['jxs_id'];
            }else{
                $postData['payeetype'][$kk]=2;//收款方是供应商
            }

        }
        $fee['payee']=$postData['payee'];//付款方id
        $fee['payeetype']=$postData['payeetype'];//付款方：1是经销商，2是供应商
        //p($postData);
        if($postData['khxqtype']==2){
            $netcount= count($khxq['jxsxt']);
        }elseif ($postData['khxqtype']==3){
            //数据处理
            if ($postData["nets"]) {
                $netsarr = explode(',', $postData["nets"]);
                $netcount=count($netsarr);
            } else {
                return json_encode(["msg" => "网点不能为空", "state" => "2"]);
            }
        }
          //客户 系统
        $feiyongcount = count($fee['feetype']);
        $procount = count($cpxq['ppnum']);
        //数据混编
        $datalist = [];
        $listnum = 0;
        $apply_id = $postData["ti_id"];
        $numnowdet = Db::table("cg_ti_list")->where(["ti_id" => $apply_id])->max("sn");

        $cbzxnum=0;
        for ($k = 0; $k < $feiyongcount; $k++) {
            $cbzxnum += count($fee['cbzx'][$k]);
        }
        if($postData['khxqtype']==2||$postData['khxqtype']==3){
            $tinum=$cbzxnum*$netcount*$procount;
        }elseif($postData['khxqtype']==1){
            $tinum=$cbzxnum*$procount;
        }

        if($postData['khxqtype']==2){ //客户详情是系统时
            for ($i = 0; $i < $netcount; $i++) {
                //$i循环网点
                //$j循环产品
                for ($j = 0; $j < $procount; $j++) {
                    //计算基准销量

                    //$j循环商品
                    for ($k = 0; $k < $feiyongcount; $k++) {
                        $cbcount = count($fee['cbzx'][$k]);
                        for ($l = 0;$l < $cbcount; $l++){   //成本中心
                            $alltouru='';
                            foreach ($fee['fRmb'] as $fk=>$fv){
                                $alltouru+=$fv;
                            }
                            $allcpzb=0;
                            foreach ($cpxq['profit'] as $zbk=>$zbv){
                                $allcpzb=floatval($allcpzb)+floatval($zbv);
                            }
                            $allroi=($postData['yesSales']-$postData['noSales'])/$alltouru*($allcpzb/$procount);
                            $aaa=($postData['yesSales']-$postData['noSales'])/$tinum*$cpxq['profit'][$j]*0.01;
                            $bbb=$fee['fRmb'][$k]*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000/(1+0.06);
                            $roi=$aaa/$bbb;
                            $roi=$roi*100;
                            $roi=round($roi, 2);

                            $hanshui=$fee['fRmb'][$k]*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000;//含税额
                            $yjsjtrfy=$hanshui/(1+0.06);//未税额，未抵扣即也是预计实际投入费用

                            /*$hanshui=$fee['fRmb'][$k]*(1+0.06);
                            $hanshui=$fee['fRmb'][$k]*(1+0.06);*/

                            /*if($yd[$j]["dikou"]){
                                $tmp["yjsjtrfy"]=$tmp["pizhunweishui"] ;
                            }else{
                                $tmp["yjsjtrfy"]= $tmp["pizhunhanshui"];
                            }*/

                            //当时特价补差类
                            if(isset($postData['fylx'])&&$postData['fylx']==4) {
                                $tmp = [
                                    "fylx"=>4,
                                    "khtype" => 2, //客户详情（经销商，系统，网点）
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "xt_id" => $khxq['jxsxt'][$i],  //系统
                                    "xt_zb" => $khxq['jxsxtzb'][$i],
                                    "net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   含税总额
                                    "amount" => $yjsjtrfy,//费用说明   未税额
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,//预计含税金额
                                    "pizhunhanshui" => $hanshui,//
                                    "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],

                                    "now_price"=>$cpxq['nowprice'][$j],//现价  ppsm
                                    "yuan_price"=>$cpxq['oldprices'][$j],//原价
                                    "zhejia"=>$cpxq['ZheJiaLv'][$j],//折价率
                                    "jizhunboxnum"=>$cpxq['cpnum'][$j],//箱数

                                    "wangdian_yuan" => $cpxq['oldprices2'][$j],  //网点原供货价
                                    "wangdian_price" => $cpxq['nowprice2'][$j],  //网点现供货价
                                    "wangdian_zhejia" => $cpxq['ZheJiaLv2'][$j],   //网点折价率
                                    "lingshou_price" => $cpxq['yls'][$j], //原零售价
                                    "huodong_price" => $cpxq['hdls'][$j],   //活动零售价
                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }else if(isset($postData['fylx'])&&$postData['fylx']==7) {
                                $tmp = [
                                    "fylx"=>7,
                                    "khtype" => 2, //客户详情（经销商，系统，网点）
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "xt_id" => $khxq['jxsxt'][$i],  //系统
                                    "xt_zb" => $khxq['jxsxtzb'][$i],
                                    "net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   含税总额
                                    "amount" => $yjsjtrfy,//费用说明   未税额
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,//预计含税金额
                                    "pizhunhanshui" => $hanshui,//
                                    "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],

                                    "wangdian_price" => $cpxq['lssghj'][$j], //零售商供货价
                                    "lingshou_price" => $cpxq['mclsj'][$j],   //卖场零售价

                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }else{
                                $tmp = [
                                    "khtype" => 2, //客户详情（经销商，系统，网点）
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "xt_id" => $khxq['jxsxt'][$i],  //系统
                                    "xt_zb" => $khxq['jxsxtzb'][$i],
                                    "net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   含税总额
                                    "amount" => $yjsjtrfy,//费用说明   未税额
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,//预计含税金额
                                    "pizhunhanshui" => $hanshui,//
                                    "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],
                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }

//p($tmp);
                            $datalist[] = $tmp;
                            $listnum++;
                        }

                    }
                }

            }
        }elseif ($postData['khxqtype']==1){
                //$i循环网点
                //$j循环产品
                for ($j = 0; $j < $procount; $j++) {
                    //计算基准销量
                    //$j循环商品
                    for ($k = 0; $k < $feiyongcount; $k++) {
                        $cbcount = count($fee['cbzx'][$k]);
                        for ($l = 0;$l < $cbcount; $l++){   //成本中心
                            $alltouru='';
                            foreach ($fee['fRmb'] as $fk=>$fv){
                                $alltouru+=$fv;
                            }

                            $allcpzb=0;
                            foreach ($cpxq['profit'] as $zbk=>$zbv){
                                $allcpzb=floatval($allcpzb)+floatval($zbv);
                            }

                            $allroi=($postData['yesSales']-$postData['noSales'])/$alltouru*($allcpzb/$procount);
                            $aaa=($postData['yesSales']-$postData['noSales'])/$tinum*$cpxq['profit'][$j]*0.01;
                            $bbb=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000/(1+0.06);//实际投入 ，未税投入
                            $roi=$aaa/$bbb;
                            $roi=$roi*100;
                            $roi=round($roi, 2);

                            $hanshui=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000;//含税额  没有系统占比
                            $yjsjtrfy=$hanshui/(1+0.06);//未税额，未抵扣即也是预计实际投入费用
                            if(isset($postData['fylx'])&&$postData['fylx']==2) {
                                $tmp = [
                                    "fylx"=>2,
                                    "khtype" => 1, //客户详情是经销商
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                    //"xt_zb" => $khxq['jxsxtzb'][$i],
                                    //"net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                    "amount" => $yjsjtrfy,
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,//预计含税金额
                                    "pizhunhanshui" => $hanshui,
                                    "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额
                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],
                                    "now_price"=>$cpxq['nowprice'][$j],//现价  ppsm
                                    "yuan_price"=>$cpxq['oldprices'][$j],//原价
                                    "zhejia"=>$cpxq['ZheJiaLv'][$j],//折价率
                                    "jizhunboxnum"=>$cpxq['cpnum'][$j],//箱数
                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"]
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];

                            }else{
                                $tmp = [
                                    "khtype" => 1, //客户详情是经销商
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                    //"xt_zb" => $khxq['jxsxtzb'][$i],
                                    //"net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                    "amount" => $yjsjtrfy,
                                    "pizhunweishui" => $yjsjtrfy,
                                    //$tmp["pizhunweishui"]

                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,//预计含税金额
                                    "pizhunhanshui" => $hanshui,
                                    "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],
                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"]
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }


                            $datalist[] = $tmp;
                            $listnum++;
                        }

                    }
                }

        }elseif ($postData['khxqtype']==3){
            for ($i = 0; $i < $netcount; $i++) {
                for ($j = 0; $j < $procount; $j++) {
                    //计算基准销量
                    //$j循环商品
                    for ($k = 0; $k < $feiyongcount; $k++) {
                        $cbcount = count($fee['cbzx'][$k]);
                        for ($l = 0;$l < $cbcount; $l++){   //成本中心
                            $alltouru='';
                            foreach ($fee['fRmb'] as $fk=>$fv){
                                $alltouru+=$fv;
                            }

                            //echo '8';
                            $allcpzb=0;
                            foreach ($cpxq['profit'] as $zbk=>$zbv){
                                $allcpzb=floatval($allcpzb)+floatval($zbv);
                            }

                            $allroi=($postData['yesSales']-$postData['noSales'])/$alltouru*($allcpzb/$procount);
                            $aaa=($postData['yesSales']-$postData['noSales'])/$tinum*$cpxq['profit'][$j]*0.01;
                            $bbb=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000/(1+0.06)/$netcount;

                            $roi=$aaa/$bbb;
                            $roi=$roi*100;
                            $roi=round($roi, 2);
                            //$hanshui=$fee['fRmb'][$k]*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000;//含税额
                            $hanshui=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000/$netcount;//含税额

                            $yjsjtrfy=$hanshui/(1+0.06);//未税额，未抵扣即也是预计实际投入费用
                            //echo 'tt';
                            /*echo $postData['fylx'];
                            p($cpxq);*/
                            if(isset($postData['fylx'])&&$postData['fylx']==4) {
                                $tmp = [
                                    "fylx"=>4,
                                    "khtype" => 3,
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "net_id" => $netsarr[$i],
                                    //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                    //"xt_zb" => $khxq['jxsxtzb'][$i],
                                    //"net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                    "amount" => $yjsjtrfy,
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,
                                    "pizhunhanshui" => $hanshui,
                                    "yjsjtrfy" => $yjsjtrfy,
                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],

                                    "now_price"=>$cpxq['nowprice'][$j],//现价  ppsm
                                    "yuan_price"=>$cpxq['oldprices'][$j],//原价
                                    "zhejia"=>$cpxq['ZheJiaLv'][$j],//折价率
                                    "jizhunboxnum"=>$cpxq['cpnum'][$j],//箱数
                                    "wangdian_yuan" => $cpxq['oldprices2'][$j],  //网点原供货价
                                    "wangdian_price" => $cpxq['nowprice2'][$j],  //网点现供货价
                                    "wangdian_zhejia" => $cpxq['ZheJiaLv2'][$j],   //网点折价率
                                    "lingshou_price" => $cpxq['yls'][$j], //原零售价
                                    "huodong_price" => $cpxq['hdls'][$j],   //活动零售价

                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"] 预计费用率
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }else if(isset($postData['fylx'])&&$postData['fylx']==7) {
                                $tmp = [
                                    "fylx"=>7,
                                    "khtype" => 3,
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "net_id" => $netsarr[$i],
                                    //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                    //"xt_zb" => $khxq['jxsxtzb'][$i],
                                    //"net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                    "amount" => $yjsjtrfy,
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,
                                    "pizhunhanshui" => $hanshui,
                                    "yjsjtrfy" => $yjsjtrfy,
                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],
                                    "wangdian_price" => $cpxq['lssghj'][$j], //零售商供货价
                                    "lingshou_price" => $cpxq['mclsj'][$j],   //卖场零售价

                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"] 预计费用率
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }else{
                                $tmp = [
                                    "khtype" => 3,
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "net_id" => $netsarr[$i],
                                    //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                    //"xt_zb" => $khxq['jxsxtzb'][$i],
                                    //"net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                    "amount" => $yjsjtrfy,
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,
                                    "pizhunhanshui" => $hanshui,
                                    "yjsjtrfy" => $yjsjtrfy,
                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],
                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"] 预计费用率
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }


                            $datalist[] = $tmp;
                            $listnum++;
                        }

                    }
                }

            }
        }

//type_id
        Db::startTrans();

        $tisq=Db::table("cg_ti")->where('id',$postData["ti_id"])->value('khtype');
        /*echo '555';
        die;*/

        try {
            $productlat=$cpxq['type']+1;
           // echo '1';
            $res1 = Db::table("cg_ti_list")->insertAll($datalist);
            //dump($res1);
            //$sq=Db::table("cg_ti_list")->where('ti_id',$postData["ti_id"])->field('ctime')->find();
           // echo '2';
            $sq=Db::table('cg_ti_list')->where('ti_id',$postData["ti_id"])->order("ctime desc")->limit(1)->select();
           // echo '3';
            $hbsq = [];
            if($sq){
                foreach ($allhb as $k=>&$v){
                    foreach ($v as $kk=>&$vv){
                        $vv['ctime']=$sq['0']['ctime'];
                        $vv['money']=$vv['factory']*$vv['num'];
                        $hbsq[]=$vv;
                    }
                }
               // echo '4';
                $res2 = Db::table("cg_ti_hb")->insertAll($hbsq);
                /*dump($res1);
                echo '5';*/
            }


        } catch (\Exception $e) {
            return $e->getMessage();die;
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试2", "state" => "2"]);
        }

        $productlat=$cpxq['type']+1;
        $tisq=Db::table("cg_ti")->where('id',$postData["ti_id"])->value('khtype');
        if(empty($tisq)){
            $data2=['id'=>$postData["ti_id"],'productlat'=>$productlat,'khtype'=>$postData['khxqtype']];
        }elseif ($tisq==$postData['khxqtype']){
            $data2=['id'=>$postData["ti_id"],'productlat'=>$productlat];
        }else{
            $data2=['id'=>$postData["ti_id"],'productlat'=>$productlat,'khtype'=>0];
        }

        $res3=Db::table("cg_ti")->update($data2);


        if ($res1) {

            Db::commit();
            return json_encode(["msg" => "操作已成功", "state" => "1"]);
        } else {
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试3", "state" => "2"]);
        }

    }  // 系统繁忙请稍后再试

  //addapply


    public function deal_hb(){
        header("Content-type:text/html;charset=utf-8");
        $postData = $this->request->post();
        //dump($postData); die;  // jxstypes  jxstypes  ypwlType 1542183518000: 1
        $wlName=array();
        $wlyptype=array();
        $jxstypes=array();
        $allhb=[];
        $allhb2=[];

        foreach ($postData as $k=>$v){
            $number2 = substr_count($k, 'ypwlType');
            if($number2){
                $strings2=str_replace("ypwlType","","$k");
                $nums2=count($wlyptype);
                $jxstypes[$strings2]=$nums2;  //处理其他参数时需要，比如处理收款方, $nums在处理收款方时当键值
                array_push($wlyptype,"$v");//系统投放网点数
            }
        }
        /*dump($wlyptype);
        p($jxstypes);*/

        //dump($postData);
//echo '1';
        $khxq=array();
        Db::startTrans();
        try {
            //p($jxstypes);
        foreach ($jxstypes as $k=>$v){
            if($wlyptype[$v]==0){
                $wlName='wlName'.$k;
            }elseif ($wlyptype[$v]==1){
                $wlName='wlName2'.$k;
            }
            if(isset($wlyptype[$v])){
                if(!empty($postData[$wlName])){
                    $jxsnum['name'][$v]=$postData[$wlName];
                    $khxq['name'][$v]=$postData[$wlName];
                }else{
                    return json_encode(["msg" => "请补全数量！", "state" => "2"]);
                }

            }else{
            }
            $wlnum='wlnum'.$k;
            if(isset($wlyptype[$v])){
                if(!empty($postData[$wlnum])){
                    $jxsnum['num'][$v]=$postData[$wlnum];
                    $khxq['num'][$v]=$postData[$wlnum];
                }else{
                    return json_encode(["msg" => "请补全数量！", "state" => "2"]);
                }

            }else{
            }

        }
            $khxq['wlyptype']=$wlyptype;

    } catch (\Exception $e) {
    echo $e->getMessage();die;
        Db::rollBack();
        return json_encode(["msg" => $e->getMessage(), "state" => 2]);
        }

        //p($wlyptype);
        $sum = 0;
        $arr=$postData['all'];

        foreach($arr as $item){
            $sum += (int) $item;
        }
        $num=count($wlyptype);
        if($num){
            $info='';
            foreach ($wlyptype as $k=>$v){


                if($info==''){  //增加物料样品类型
                    $info = 'wlName:'.$khxq['name'][$k].',num:'.$jxsnum['num'][$k].',wlyptype:'.$v;
                }else{
                    $info = $info.';wlName:'.$khxq['name'][$k].',num:'.$jxsnum['num'][$k].',wlyptype:'.$v;
                }
            }
            return json_encode(["msg" => "操作已成功", "state" => "1","sum"=>$sum,"info"=>$info]);
        }else{
            return json_encode(["msg" => "请添加样品或物料！", "state" => "2"]);
        }

       /* $num=count($wlName);

        if($num){
            $info='';
            foreach ($wlName as $k=>$v){
                if($info==''){
                    $info = 'wlName:'.$v.',num:'.$wlnum[$k];
                }else{
                    $info = $info.';wlName:'.$v.',num:'.$wlnum[$k];
                }
            }

            return json_encode(["msg" => "操作已成功", "state" => "1","sum"=>$sum,"info"=>$info]);
        }else{
            return json_encode(["msg" => "请添加样品或物料！", "state" => "2"]);
        }
        return json_encode(["msg" => "操作已成功", "state" => "1"]);*/
    }
    //异动  //网点产品的异动
    public function yidong22($aid)
    {
        Db::startTrans();
        try {
        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti next", "ap.new=next.id", "LEFT")
            ->join("ti_state s", "ap.status=s.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("job_employee je", "ec.id=je.employee_id", "LEFT")
            ->join("job j", "je.job_id=j.id", "LEFT")
            ->join("department_employee de", "ec.id=de.employee_id", "LEFT")
            ->join("department d", "de.department_id=d.id", "LEFT")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("cg_market_zoning jz", "jx.zoning=jz.id", "LEFT")
            ->join("cg_market_provice jp", "jx.provice=jp.id", "LEFT")
            ->join("cg_market_city jc", "jx.city=jc.id", "LEFT")
            ->where(["ap.id" => $aid, "de.index" => 1])
            ->field("ap.title,ap.sn as no,yuan.sn as yuanno,next.sn as nextno,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.ctime,jx.title as jingxiao,jz.title as fenqu,jp.title as sheng,jc.title as shi")
            ->find();
        $apply["created_on"] = date("Y-m-d", $apply["ctime"]);
        $this->assign("apply", $apply);


        $applynet = Db::table("cg_ti")->query("select apd.net_id,sum(apd.totalExpectedSales) as sellnums,sum(apd.bucha) as buchas,sum(apd.amount) as zonges,sum(apd.hanshui) as hanshuis,sum(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoues from cg_ti as ap inner join cg_ti_list as apd on apd.ti_id=ap.id inner join pro_products as p on apd.product=p.id where ap.id=$aid group by apd.net_id ");
        $this->assign("applynet", $applynet);
        //p($applynet);   //有数据
        $net_num = count($applynet);
        $this->assign("net_num", $net_num);
        $xiao = 0;
        for ($i = 0; $i < count($applynet); $i++) {
            $xiao += $applynet[$i]["xiaoshoues"];
        }
        $this->assign("xiao", $xiao);
        /*$applyde = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")
            ->join("pro_products p", "apd.product=p.id")
            ->join("pro_sku sk", "p.sku_id=sk.id")
            ->join("pro_series ps", "sk.series_id=ps.id")
            ->join("pro_price pp", "pp.pid=p.id")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->join("cg_paymethod cp", "apd.paymethod=cp.id")
            ->join("cg_fijiru cf", "apd.project=cf.id")
            ->join("cg_fijiruzd fj", "apd.jrbm=fj.id")->join("department d", "fj.title=d.id")
            ->where(["ap.id" => $aid])->order("apd.net_id,apd.product")
            ->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as hexiao_time,apd.totalExpectedSales,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.pizhunweishui as pifuzonge,apd.pizhunhanshui as hanshui,apd.feiyongmiaoshu as remark,apd.head as fuzeren,cp.title as zffs,cf.title as jrfa,(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoue,apd.brief as  beizhu,d.de_name,apd.shuilv,apd.isVAT as dikou,apd.zhejia,apd.status as tag,apd.paymethod as zfid")
            ->select();*/


            $applyde = Db::table("cg_ti")->alias("ap")
                ->join("cg_ti_list apd", "apd.ti_id=ap.id")
                ->join("cg_net n", "apd.net_id=n.id", "LEFT")
                ->join("cg_system s", "n.system_id=s.id", "LEFT")
                ->join("pro_products p", "apd.product=p.id")
                ->join("pro_sku sk", "p.sku_id=sk.id")
                ->join("pro_series ps", "sk.series_id=ps.id")
                ->join("pro_price pp", "pp.pid=p.id")
                ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
                ->join("cg_paymethod cp", "apd.paymethod=cp.id")
                //->join("cg_fijiru cf", "apd.project=cf.id")  //此处导致产品数据为空 ，检查原因： 费用计入方案 new tpm 没有
//                ->join("cg_fijiruzd fj", "apd.jrbm=fj.id")  //  apd.jrbm  检查原因：费用计入部门 new tpm 没有
//                ->join("department d", "fj.title=d.id")
                ->where(["ap.id" => $aid]) // d.de_name, cf.title as jrfa,
                ->order("apd.net_id,apd.product")  //
                ->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as hexiao_time,apd.totalExpectedSales,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.pizhunweishui as pifuzonge,apd.pizhunhanshui as hanshui,apd.feiyongmiaoshu as remark,apd.head as fuzeren,cp.title as zffs,(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoue,apd.brief as  beizhu,apd.shuilv,apd.isVAT as dikou,apd.zhejia,apd.status as tag,apd.paymethod as zfid")
               // ->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as hexiao_time,apd.totalExpectedSales,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.pizhunweishui as pifuzonge,apd.pizhunhanshui as hanshui,apd.feiyongmiaoshu as remark,apd.head as fuzeren,cp.title as zffs,cf.title as jrfa,(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoue,apd.brief as  beizhu,d.de_name,apd.shuilv,apd.isVAT as dikou,apd.zhejia,apd.status as tag,apd.paymethod as zfid")
                ->select();

// fj. d.
    //        p($applyde);
//        echo Db::table("cg_ti")->alias("ap")->getLastSql();die;
         //p($applyde); 此处无数据，请查明原因
        for ($i = 0; $i < count($applyde); $i++) {
            $applyde[$i]["start_time"] = date("Y-m-d", $applyde[$i]["start_time"]);
            $applyde[$i]["end_time"] = date("Y-m-d", $applyde[$i]["end_time"]);
            $applyde[$i]["hexiao_time"] = date("Y-m-d", $applyde[$i]["hexiao_time"]);
        }
        } catch (\Exception $e) {

            Db::rollBack();//echo $e->getMessage();exit;
            return json_encode(["msg" =>$e->getMessage(), "state" => 2]);
        }

        $this->assign("applyde", $applyde);

        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);
        $this->assign("aid", $aid);

        return $this->fetch();
    }

    //查看详情
    public function view(){
        $id = $this->request->param('id');

        $logs=$this->getlog($id);
        $this->assign("logs",$logs);
        $data = db('cg_ti')->where('id',$id)->find();
        $data['zoning'] = db('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['provice'] = db('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['city'] = db('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['cusername'] = db('employee')->where('id',$data['cuser'])->value('em_name');
        switch ($data['status']){
            case 2:
                $data['status_title'] = '已打回';
                break;
            case 3:
                $data['status_title'] = '区域领导审批';
                break;
            case 4:
                $data['status_title'] = '拆分人审批';
                break;
            case 5:
                $data['status_title'] = '集团领导审批';
                break;
            case 6:
                $data['status_title'] = '抄送';
                break;
            case 7:
                $data['status_title'] = '已归档';
                break;
            case 8:
                $data['status_title'] = '已作废';
                break;
            case 9:
                $data['status_title'] = '已否决';
                break;
            default:
                $data['status_title'] = '草稿';
        }
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->join('employee t3','t3.id=t2.employee_id')->where('t3.id',$data['cuser'])->value('t.job_name');

        //查询明细列表
        if($data['arealat']==1){
            $list = db('cg_ti_list')->where('ti_id',$id)->group('jxs_id')->field('jxs_id')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('yjsjtrfy');//小计-含税税费用金额
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang'];//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = round(db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('yujiroi'),2);//小计-预计rio
                $list[$k]['st_yihexiao'] = round(db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('hx_yihexiao'),2);//小计-已核销金额
                $list[$k]['st_shijixiaoliang'] = round(db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('shijixiaoliang'),2);//小计-实际销量
                $list[$k]['st_xiaoshoudachenglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_shijixiaoliang']/$list[$k]['st_yujixiaoliang']*100:0;
            }
        }else{
            $list = db('cg_ti_list')->where('ti_id',$id)->group('net_id')->field('net_id')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('yjsjtrfy');//小计-实际投入费用
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang']*100:0;//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = round(db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('yujiroi'),2);//小计-预计rio
                $list[$k]['st_yihexiao'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('hx_yihexiao');//小计-已核销
                $list[$k]['st_shijixiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('shijixiaoliang');//小计-实际销量
                $list[$k]['st_xiaoshoudachenglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_shijixiaoliang']/$list[$k]['st_yujixiaoliang']*100:0;
            }
        }
        foreach($list as $k=>$v){
            foreach($v['_child'] as $k1=>$v1){
                if($v1['status']==1){ //异动
                    $start = db('cg_ti_list')->where('id',$v1['refer_id'])->value('start');
                    $end = db('cg_ti_list')->where('id',$v1['refer_id'])->value('end');
                    if($start != $v1['start']&&$end!=$v1['end']){
                        $v['_child'][$k1]['start'] = $start;
                        $v['_child'][$k1]['end'] = $end;
                        $v['_child'][$k1]['ydstart'] = $v1['start'];
                        $v['_child'][$k1]['ydend'] = $v1['end'];
                    }
                }
                $v['_child'][$k1]['eauser_title'] = db('employee')->where('id',$v1['eauser'])->value('em_name');
                if($v1['jxs_id']){
                    $v['_child'][$k1]['jxs_title'] = db('cg_jxs')->where('id',$v1['jxs_id'])->value('title');
                }else{
                    $v['_child'][$k1]['jxs_id'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v1['net_id'])->value('t.jxs');
                    $v['_child'][$k1]['jxs_title'] = db('cg_jxs')->where('id',$v['_child'][$k1]['jxs_id'])->value('title');
                }
                $v['_child'][$k1]['feetype'] = db('cg_feiyongkemu3')->where('id',$v1['feetype'])->value('title');
                $v['_child'][$k1]['paymethod_title'] = db('cg_paymethod')->where('id',$v1['paymethod'])->value('title');

                $v['_child'][$k1]['jrbm_puser_name'] = db('cg_fijiruzd t')
                    ->join('employee t2','t2.id=t.puser')
                    ->where('t.title',$v1['jrbm'])
                    ->value('t2.em_name');//费用计入部门修改人
                $v['_child'][$k1]['jrbm'] = db('department t')
                    ->join('cg_fijiruzd t2','t2.title = t.id')
                    ->where('t2.id',$v1['jrbm'])
                    ->value('t.de_name');

                $v['_child'][$k1]['jrbm_dp'] = db('cg_fijiru')->where('id',$v1['project'])->value('title');
                $v['_child'][$k1]['jrbm_dp_puser'] = db('cg_fijiru t')->join('employee t2','t2.id=t.puser')->where('t.id',$v1['project'])->value('t2.em_name');
                $v['_child'][$k1]['brand'] = db('pro_brands')->where('id',$v1['brand'])->value('brand_name');
                if($v1['net_id'])
                    $v['_child'][$k1]['net_title'] = db('cg_net')->where('id',$v1['net_id'])->value('title');
                $v['_child'][$k1]['productlatval'] = $this->productlatval($v1);
                $v['_child'][$k1]['yujifeiyonglv'] = $v1['totalExpectedSales']?round($v1['yjsjtrfy']/$v1['hanshui'],2)*100:0;
                $v['_child'][$k1]['xiaoshoudachenglv'] = $v1['totalExpectedSales']?round($v1['fb_shijixiaoliang']/$v1['totalExpectedSales'],2)*100:0;
                $v['_child'][$k1]['gys_name'] = db('gys')->where('id',$v1['gys'])->value('gys_name');
            }
            $list[$k] = $v;
        }
        $data['list'] = $list;

        //查询供应商数量
        $data['net_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('net_id is not null')->group('net_id')->count();
        $data['brand_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('brand is not null')->group('brand')->count();
        $data['category_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('category is not null')->group('category')->count();
        $data['series_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('series is not null')->group('series')->count();
        $data['sku_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('sku is not null')->group('sku')->count();
        $data['product_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('product is not null')->group('product')->count();
        $data['feetype_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('feetype is not null')->group('feetype')->count();
        $data['arealat_title'] = $data['arealat']==1?'经销商名称':'网点名称';
        if($data['productlat']==1) { //产品纬度
            $data['product_title'] = '品牌';
        }elseif($data['productlat']==2) {
            $data['product_title'] = '品类';
        }elseif($data['productlat']==3) {
            $data['product_title'] = '系列';
        }elseif($data['productlat']==4) {
            $data['product_title'] = 'sku';
        }elseif($data['productlat']==5) {
            $data['product_title'] = '产品';
        }
        $data['amounts'] = db('cg_ti_list')->where('ti_id',$id)->sum('amount');
        $data['hanshui']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hanshui');//总计-含税费用金额
        $data['shijitourufeiyong']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('yjsjtrfy');//总计-实际投入费用
        $data['shijitourufeiyong'] = round($data['shijitourufeiyong'],2);
        $data['yujixiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalExpectedSales');//总计-预计销量
        $data['yujixiaoliang'] = round($data['yujixiaoliang'],2);
        $data['yujifeiyonglv'] = $data['yujixiaoliang']?$data['hanshui']/$data['yujixiaoliang']*100:0;//总计-预计费用率
        $data['yujifeiyonglv'] = round($data['yujifeiyonglv'],2);
        $data['2srjizhun'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('2srjizhun');//总计-2sr基准销量
        $data['jizhunxiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalBenchmarkSales');//总计-基准销量
        $data['jizhunxiaoliang'] = round($data['jizhunxiaoliang'],2);
        $data['yujiroi'] = round(db('cg_ti_list')->where(['ti_id'=>$id])->sum('yujiroi'),2);//总计-预计rio
        $data['yihexiao'] = round(db('cg_ti_list')->where(['ti_id'=>$id])->sum('hx_yihexiao'),2);//总计-已核销
        $data['shijixiaoliang'] = round(db('cg_ti_list')->where(['ti_id'=>$id])->sum('shijixiaoliang'),2);//总计-实际销量
        $data['xiaoshoudachenglv'] = $data['yujixiaoliang']?$data['shijixiaoliang']/$data['yujixiaoliang']*100:0;

        $data['yhx'] = db('cg_ti_hexiao_list t')
            ->join('cg_ti_list t2','t2.id=t.list_id')
            ->where('t2.ti_id',$id)->count();
//        echo db('cg_ti_list')->getLastSql();

        $this->assign('data',$data);
        $fei=db("cg_ti_list")->alias("t")->join("cg_feiyongkemu3 f3","t.feetype=f3.id")->group("f3.id")->where(["ti_id"=>$id])->field("f3.title,sum(pizhunhanshui) as jine")->select();
        $this->assign("fei",$fei);
        //查询审批意见
        $wf_id = db('cg_workflow')->where(['ywlx'=>2,'yw_id'=>$id])->value('id');
        $spyj = db('cg_workflow_spyj')->where('wf_id',$wf_id)->order('spsj asc')->select();
        $this->assign('spyj',$spyj);
        $export = $this->request->get('export');
        if($export){
            //根据经销商查询分区省份和城市
            $city = db('cg_jxs t')->join('cg_market_city t2','t.city=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $provice = db('cg_jxs t')->join('cg_market_provice t2','t.provice=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $zoning = db('cg_jxs t')->join('cg_market_zoning t2','t.zoning=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $this->assign([
                'city'=>$city,
                'provice'=>$provice,
                'zoning'=>$zoning,
            ]);

            ob_end_clean();
            ob_start();

            header('Content-Type : application/vnd.ms-excel');
            header('Content-Disposition:attachment;filename="'.iconv('utf-8','gbk',$data['sn'].'-'.date("Y年m月j日")).'.xls"');
            return $this->fetch('view_export');
        }else{
            //查询核销编号
            $hxsn = db('cg_ti_hexiao t')
                ->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')
                ->join('cg_ti_list t3','t3.id=t2.list_id')
                ->where('t3.ti_id',$id)
                ->field('t.id,t.sn')
                ->select();
            $this->assign('hxsn',$hxsn);
            //查询反馈编号
            $fbsn = db('all_ti_feeback_list t')
                ->join('cg_ti t2','t2.id=t.apply_id')
                ->where(['type'=>1,'t2.id'=>$id])
                ->field('t.id,t.no')
                ->find();
            $this->assign('fbsn',$fbsn);
            return $this->fetch();
        }
    }

    //异动  //网点产品的异动  a
    public function yidong($aid)
    {
        Db::startTrans();
        try {
            $apply = Db::table("cg_ti")->alias("ap")
                ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
                ->join("cg_ti next", "ap.new=next.id", "LEFT")
                ->join("ti_state s", "ap.status=s.id")
                ->join("employee ec", "ap.cuser=ec.id", "LEFT")
                ->join("job_employee je", "ec.id=je.employee_id", "LEFT")
                ->join("job j", "je.job_id=j.id", "LEFT")
                ->join("department_employee de", "ec.id=de.employee_id", "LEFT")
                ->join("department d", "de.department_id=d.id", "LEFT")
                ->join("cg_jxs jx", "ap.jxs_id=jx.id")
                ->join("cg_market_zoning jz", "jx.zoning=jz.id", "LEFT")
                ->join("cg_market_provice jp", "jx.provice=jp.id", "LEFT")
                ->join("cg_market_city jc", "jx.city=jc.id", "LEFT")
                ->where(["ap.id" => $aid, "de.index" => 1])
                ->field("ap.productlat,ap.arealat,ap.title,ap.sn as no,yuan.sn as yuanno,next.sn as nextno,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.ctime,jx.title as jingxiao,jz.title as fenqu,jp.title as sheng,jc.title as shi")
                ->find();
            //productlat 产品维度、1品牌、2品类、3系列、4sku、5单品
            //arealat 区域纬度：1经销商类，2网点类  暂时没有
            $apply["created_on"] = date("Y-m-d", $apply["ctime"]);
            $this->assign("apply", $apply);
            $sql1="";
            $applynet = Db::table("cg_ti")
                ->query("select apd.net_id,sum(apd.totalExpectedSales) as sellnums,sum(apd.bucha) as buchas,sum(apd.amount) as zonges,sum(apd.hanshui) as hanshuis,sum(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoues from cg_ti as ap inner join cg_ti_list as apd on apd.ti_id=ap.id inner join pro_products as p on apd.product=p.id where ap.id=$aid group by apd.net_id ");
//p($applynet);
            $this->assign("applynet", $applynet);
            $net_num = count($applynet);
            $this->assign("net_num", $net_num);
            $xiao = 0;
            for ($i = 0; $i < count($applynet); $i++) {
                $xiao += $applynet[$i]["xiaoshoues"];
            }
            $this->assign("xiao", $xiao);
            $applyde = Db::table("cg_ti")->alias("ap")
                ->join("cg_ti_list apd", "apd.ti_id=ap.id")
                ->join("cg_net n", "apd.net_id=n.id", "LEFT")      // 网点
                ->join("cg_system s", "apd.xt_id=s.id", "LEFT")  // 系统
                ->join("cg_jxs j", "apd.jxs_id=j.id", "LEFT")  // 经销商
                ->join("pro_products p", "apd.product=p.id","LEFT")
                ->join("pro_sku sk", "apd.sku=sk.id","LEFT")  //
                ->join("pro_series ps", "apd.series=ps.id","LEFT")
                ->join("pro_category cat", "apd.category=cat.id","LEFT")  //
                ->join("pro_brands bra", "apd.brand=bra.id","LEFT")
                ->join("pro_price pp", "pp.pid=apd.id","LEFT")  //
                ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
                ->join("cg_paymethod cp", "apd.paymethod=cp.id")
                ->where(["ap.id" => $aid])
                ->order("apd.id")
                ->field("apd.yesSales,apd.yjsjtrfy,apd.yujiroi, apd.totalBenchmarkSales,ap.sn as no,n.title as net,s.title as xitong,ps.series_name,p.pro_name,bra.brand_name,cat.category_name,sk.sku_name,j.title as jxs,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,apd.start as start_time,apd.end as end_time,apd.expCanTime as hexiao_time,apd.totalExpectedSales,apd.bucha,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.pizhunweishui as pifuzonge,apd.pizhunhanshui as hanshui,apd.feiyongmiaoshu as remark,apd.head as fuzeren,cp.title as zffs,apd.brief as  beizhu,apd.shuilv,apd.isVAT as dikou,apd.zhejia,apd.status as tag,apd.paymethod as zfid")
                // ->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as hexiao_time,apd.totalExpectedSales,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.pizhunweishui as pifuzonge,apd.pizhunhanshui as hanshui,apd.feiyongmiaoshu as remark,apd.head as fuzeren,cp.title as zffs,cf.title as jrfa,(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoue,apd.brief as  beizhu,d.de_name,apd.shuilv,apd.isVAT as dikou,apd.zhejia,apd.status as tag,apd.paymethod as zfid")
                ->select();
           // p($applyde);
            $list2 = db('cg_ti_list')->where('ti_id',$aid)->order('net_id asc')->select();
            $xxxxnum=count($applyde);
            foreach ($applyde as $k2=>&$v2) {
                if ($xxxxnum != 0) {
                    $v2['hdxl'] = round($v2['yesSales'] / $xxxxnum, 2);
                } else {
                    $v2['hdxl'] = $v2['yesSales'];
                }
                if (!empty($v2['hdxl'])) {
                    $v2['yjfyl'] = round(100 * $v2['yjsjtrfy'] / $v2['hdxl'], 2) . '%';
                } else {
                    $v2['yjfyl'] = 0;
                }
            }
            for ($i = 0; $i < count($applyde); $i++) {
                $v2['yjfyl']=round(100*$v2['yjsjtrfy']/$v2['hdxl'],2).'%';
                $applyde[$i]["start_time"] = date("Y-m-d", $applyde[$i]["start_time"]);
                $applyde[$i]["end_time"] = date("Y-m-d", $applyde[$i]["end_time"]);
                $applyde[$i]["hexiao_time"] = date("Y-m-d", $applyde[$i]["hexiao_time"]);
            }
        } catch (\Exception $e) {
            Db::rollBack();//echo $e->getMessage();exit;
            return json_encode(["msg" =>$e->getMessage(), "state" => 2]);
        }
        $this->assign("applyde", $applyde);  // applynet
        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);
        $this->assign("aid", $aid);
        return $this->fetch();
    }
  //  以上为异动
    //异动操作
    public function yidongchuli()
    {
        $request = Request::instance();


        $data = $request->post();

        if ($data) {
            //print_r($data);exit;
            $yd = [];
            $yddid = [];
            $j = 0;
           // echo 'h';

            for ($i = 0; $i < count($data["did"]); $i++) {
                if (trim($data["yidongyuanyin"][$i])) {
                    $yd[$j]["did"] = $data["did"][$i];
                    $yd[$j]["zonge"] = $data["zonge"][$i];
                    /*if ($data["bucha"][$i]) {
                        $yd[$j]["bucha"] = $data["bucha"][$i];
                    } else {
                        $yd[$j]["bucha"] = null;
                    }*/
                    $yd[$j]["dikou"] = $data["dikou"][$i];
                    $yd[$j]["shuilv"] = $data["shuilv"][$i];
                    $yd[$j]["zfid"] = $data["zfid"][$i];
                    $yd[$j]["start_time"] = $data["start_time"][$i];
                    $yd[$j]["end_time"] = $data["end_time"][$i];
                    $yd[$j]["hexiao_time"] = $data["hexiao_time"][$i];
                    $yd[$j]["yidongyuanyin"] = $data["yidongyuanyin"][$i];
                    $yddid[$j] = $data["did"][$i];
                    $j++;
                }
            }

            //echo 'k2';die;
//print_r($yd);exit;
            if (!$yd) {
                return json_encode(["msg" => "至少一条明细发生异动", "state" => 2]);
            }
            $aid = $data["aid"];
//            echo 'de';
//            print_r($yd);exit;
            Db::startTrans();

            try {
                //原单
                $apply = Db::table("cg_ti")->where(["id" => $aid])->find();
                //echo 'eee21';die;
                //生成单号

                $strnum = $this->produceSN();
                //echo 'eee2';die;
                $addapply = $apply;
                unset($addapply["id"]);
                $addapply["sn"] = $strnum;
                $addapply["ctime"] = time();
                $addapply["ptime"] = time();
                $addapply["old"] = $aid;
                $addapply["status"] = 1;
                $addapply["attach"] = $data["attach"];
                $addapply["cate_id"] = 2;
                $addapply["cuser"] = Session::get("employee_id");
                $addapply["puser"] = Session::get("employee_id");
                /*echo 'eee';die;
                print_r($addapply);exit;*/
                $res1 = Db::table("cg_ti")->insertGetId($addapply);
                //echo $res1;exit;
                //原明细
                $applymx = Db::table("cg_ti_list")->where(["ti_id" => $aid])->select();
                Db::table("cg_ti")->where(["id" => $aid])->update(["is_ydqx"=>1]);
                //生成新明细
                $datayd = [];
                for ($i = 0; $i < count($applymx); $i++) {
                    if (in_array($applymx[$i]["id"], $yddid)) {
                        //异动
                        $tmp = $applymx[$i];
                        for ($j = 0; $j < count($yd); $j++) {
                            //echo 'k';die;
                            if ($yd[$j]["did"] == $tmp["id"]) {

                                //echo 'k2';die;
                                //异动修改
                                //
                                //计算折算率  zong=qian*bucha*zhejia/100
                                /*if ($tmp["bucha"]) {

                                    $xiangqian = $tmp["pizhunweishui"] * 100 / $tmp["zhejia"] / $tmp["bucha"];

                                    $tmp["zhejia"] = $yd[$j]["zonge"] / $yd[$j]["bucha"] * 100 / $xiangqian;
                                } else {
                                    $tmp["zhejia"] = null;
                                }*/
                               // echo 'k3';
                                $tmp["amount"] = $yd[$j]["zonge"];
                                //$tmp["bucha"] = $yd[$j]["bucha"];
                                $tmp["isVAT"] = $yd[$j]["dikou"];
                                $tmp["shuilv"] = $yd[$j]["shuilv"];
                                $tmp["hanshui"] = $yd[$j]["zonge"] + $yd[$j]["zonge"] * $yd[$j]["shuilv"] / 100;
                                $tmp["paymethod"] = $yd[$j]["zfid"];
                                $tmp["start"] = strtotime($yd[$j]["start_time"]);
                                $tmp["end"] = strtotime($yd[$j]["end_time"]);
                                $tmp["expCanTime"] = strtotime($yd[$j]["hexiao_time"]);
                                $tmp["ydreason"] = $yd[$j]["yidongyuanyin"];
                                $tmp["status"] = 1;
                                $tmp["pizhunweishui"] = $yd[$j]["zonge"];
                                $tmp["pizhunhanshui"] = $yd[$j]["zonge"] + $yd[$j]["zonge"] * $yd[$j]["shuilv"] / 100;
                                if($yd[$j]["dikou"]){
                                    $tmp["yjsjtrfy"]=$tmp["pizhunweishui"] ;
                                }else{
                                    $tmp["yjsjtrfy"]= $tmp["pizhunhanshui"];
                                }
                                //预计费用率

                                /*echo 'a4';
                                p($tmp);
                                p($tmp["totalExpectedSales"]);
                                echo $tmp["totalExpectedSales"];die;*/
                                //p($tmp);
                                $tmp["yujifeiyonglv"]=$tmp["yjsjtrfy"]/$tmp["totalExpectedSales"]*100; //除数不能为0，totalExpectedSales  总预计销量 即yesSales
                               // echo 'a5';die;
                                //预计roi
                                //$yujirois=($boxnum*$prolist[$j]["now_price"]* $data["boxunit"][$j]-$basee)*$prolist[$j]["pbmaoli"]/100;
                                $profit=db("pro_products pp")->join("pro_sku sk","pp.sku_id=sk.id")
                                    ->join("pro_series ps","sk.series_id=ps.id")->join("pro_category pc","ps.category_id=pc.id")
                                    ->join("pro_brands pb","pc.brand_id=pb.id")->where(["pp.id"=>$tmp["product"]])->value("pb.profit");
                                $tmp["yujiroi"]=($tmp["totalExpectedSales"]-$tmp["totalBenchmarkSales"])*$profit/100/$tmp["yjsjtrfy"];
                                //echo 'k4';die;
                            }
                        }
                        $tmp["refer_id"] = $tmp["id"];
                        unset($tmp["id"]);
                        $datayd[$i] = $tmp;

                    } else {
                        $tmp = $applymx[$i];
                        $tmp["refer_id"] = $tmp["id"];
                        $tmp["status"] = 0;
                        $tmp["ydreason"] = null;
                        unset($tmp["id"]);
                        $datayd[$i] = $tmp;
                    }
                    $datayd[$i]["ti_id"] = $res1;
                }
                //print_r($datayd);exit;
                $res2 = Db::table("cg_ti_list")->insertAll($datayd);

                $ys=$this->tiys($res1);
                if($ys===0&&$data["state"]==3)
                    return json_encode(["msg" => "尚未设定ti预算格式无法提交", "state" => 2]);
                //$res1 = Db::table("cg_ti")->update($dataup);

                $savetype = $data["state"];
                if ($savetype == '3') {
                    if($ys){
                        Db::table("yusuan_detail")->insertAll($ys);
                    }

                }
                if($data["state"]==3){
                    $flowId = db('cg_workflowset')->where(['id' => '21'])->value('flow_id');
                    $datawf = [];
                    $datawf['accessToken'] = session('accessToken');
                    $datawf['flowId'] = $flowId;
                    $datawf = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf', $datawf);
                    $insert = [];
                    //$insert['ywlx'] = 21;  //原来的非常规异动
                    $insert['ywlx'] = 21;
                    $row = db('cg_ti')->where('id', $res1)->field('title,sn')->find();
                    $insert['rwmcjbh'] = $row['title'] . '[' . $row['sn'] . ']';
                    $insert['yw_id'] = $res1;
                    $insert['status'] = 1;
                    $insert['department_id'] = db('department_employee')->where(['index' => 1, 'employee_id' => session('employee_id')])->value('department_id');
                    $insert['sqr_id'] = session('employee_id');
                    $insert['workId'] = $datawf->workId;
                    $insert['trackId'] = $datawf->flowNode->trackId;
                    db('cg_workflow')->insert($insert);
                    db('cg_ti')->where('id', $res1)->update(["status"=>3]);
                }
            } catch (\Exception $e) {

                Db::rollBack();
                echo $e->getMessage();exit;
                return json_encode(["msg" =>$e->getMessage(), "state" => 2]);
            }
            //echo 'rrr';die;
            if ($res1 && $res2) {

                Db::commit();


                return json_encode(["msg" => "", "state" => 1]);
            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }

            //print_r($datayd);exit;
        } else {
            return json_encode(["msg" => "请正确提交", "state" => 2]);
        }
    }

    //获取单挑明细信息
    public function dantiaomingxi($did)
    {
        $res = Db::table("cg_ti_list")->where(["id" => $did])
            ->field("(fb_shijitourufeiyong) as fankuijine,hx_sqz,hx_yihexiao")->find();
        if ($res["hx_sqz"])
            $sq = $res["hx_sqz"];
        else
            $sq = 0;
        if ($res["hx_yihexiao"])
            $yh = $res["hx_yihexiao"];
        else
            $yh = 0;
        $res["hexiao"] = $sq + $yh;
        $res["weihe"] = $res["fankuijine"] - $res["hexiao"];
        return json_encode($res);

    }

    //不予核销
    public function nohexiao($did, $state)
    {
        Db::startTrans();
        try {
            Db::table("cg_ti_list")->where(["id" => $did])->update(["hx_status" => 2]);
            // echo Db::table("cg_ti_list")->getLastsql();exit;
        } catch (\Exception $e) {
            //echo $e->getMessage();
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
        Db::commit();
        return json_encode(["msg" => "", "state" => 1]);

    }

    //核销预览
    public function hexiaoscan()
    {
        $request = Request::instance();


        $data = $request->post();
        $this->assign("zongbeizhu", $data["zongbeizhu"]);
        //print_r($data);
        //处理接收数据
        $postdata = [];
        for ($i = 0; $i < count($data["dids"]); $i++) {
            $postdata[$i] = ["did" => $data["dids"][$i], "isfa" => $data["isfa"][$i],
                "fapiao" => $data["fapiao"][$i], "shuilv" => $data["shuilv"][$i], "isdi" => $data["isdi"][$i],
                "weishui" => $data["weishui"][$i], "shuijin" => $data["shuilv"][$i] * $data["weishui"][$i] / 100,
                "hanshui" => $data["shuilv"][$i] * $data["weishui"][$i] / 100 + $data["weishui"][$i], "beizhu" => $data["beizhu"][$i], "zfid" => $data["zfid"][$i]
            ];
        }
        $this->assign("postdata", $postdata);
        $eid = Session::get("employee_id");
        $aid = $data["aid"];
        $user = Db::table("employee")->alias("e")
            ->join("job_employee je", "e.id=je.employee_id", "LEFT")
            ->join("job j", "je.job_id=j.id", "LEFT")
            ->join("department_employee de", "e.id=de.employee_id", "LEFT")
            ->join("department d", "de.department_id=d.id", "LEFT")
            ->where(["e.id" => $eid, "de.index" => 1, "d.is_actived" => 1, "d.is_deleted" => 0, "j.is_actived" => 1, "j.is_deleted" => 0])
            ->field("e.id,e.em_name,d.de_name,j.job_name")
            ->find();
        $this->assign("user", $user);
        $time = date("Y-m-d H:i");
        $this->assign("time", $time);
        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->where(["ap.id" => $aid])->field("jx.title as jxs,jx.sn,ec.em_name as cname,jx.id as jxs_id")->find();

        $this->assign("apply", $apply);

        $dids = implode(',', $data["dids"]);

        $ade = Db::table("cg_ti_list")->alias("apd")
            ->join("cg_ti ap", "apd.ti_id=ap.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")
            ->join("pro_products p", "apd.product=p.id", "LEFT")
            ->join("pro_sku sk", "p.sku_id=sk.id", "LEFT")
            ->join("pro_series ps", "sk.series_id=ps.id", "LEFT")
            ->join("pro_category pc", "ps.category_id=pc.id", "LEFT")
            ->join("pro_brands pb", "pc.brand_id=pb.id", "LEFT")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->where("ap.id=$aid and apd.id in($dids)")
            ->field("apd.id,ap.sn as no,apd.sn as detail_no,ec.em_name as cname,n.title as net_name,s.title as sys_name,pb.brand_name,f3.title as kemu3,apd.fb_shijiweishui as fankuijine,apd.fb_hanshui as fankuihanshui,apd.hx_yihexiao,apd.hx_sqz,apd.paymethod as zfid,apd.start as start_time,apd.fb_shuilv as fankuishuilv,ap.id as apid,apd.fb_shijitourufeiyong,apd.fb_isVAT")
            ->select();
        for ($i = 0; $i < count($ade); $i++) {
            $ade[$i]["hexiao"] = $ade[$i]["hx_yihexiao"] + $ade[$i]["hx_sqz"];
            $ade[$i]["weihe"] = $ade[$i]["fankuijine"] - $ade[$i]["hexiao"];
            $ade[$i]["start_time"] = date("Y-m-d", $ade[$i]["start_time"]);
        }
        // print_r($ade);exit;
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);
        $this->assign("ade", $ade);
        $this->assign("aid", $aid);
        $datastr = json_encode($data);
        $this->assign("datastr", $datastr);
        //print_r($data);
        return $this->fetch();
    }

    //取消
    public function quxiao($aid)
    {
        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti next", "ap.new=next.id", "LEFT")
            ->join("ti_state s", "ap.status=s.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("job_employee je", "ec.id=je.employee_id", "LEFT")
            ->join("job j", "je.job_id=j.id", "LEFT")
            ->join("department_employee de", "ec.id=de.employee_id", "LEFT")
            ->join("department d", "de.department_id=d.id", "LEFT")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("cg_market_zoning jz", "jx.zoning=jz.id", "LEFT")
            ->join("cg_market_provice jp", "jx.provice=jp.id", "LEFT")
            ->join("cg_market_city jc", "jx.city=jc.id", "LEFT")
            ->where(["ap.id" => $aid, "de.index" => 1])
            ->field("ap.title,ap.sn as no,yuan.sn as yuanno,next.sn as nextno,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.ctime,jx.title as jingxiao,jz.title as fenqu,jp.title as sheng,jc.title as shi")
            ->find();
        $apply["created_on"] = date("Y-m-d", $apply["ctime"]);
        $this->assign("apply", $apply);
        /*$netsql="select apd.net_id,sum(apd.totalExpectedSales) as sellnums,sum(apd.bucha) as buchas,sum(apd.pizhunweishui) as zonges,
sum(apd.pizhunhanshui) as hanshuis,sum(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoues from cg_ti as ap 
inner join cg_ti_list as apd on apd.ti_id=ap.id inner join pro_products as p on apd.product=p.id where ap.id=$aid group by apd.net_id ";

        $applynet = Db::table("ti_apply")->query($netsql);*/

        $applynet = Db::table("cg_ti")
            ->query("select apd.net_id,sum(apd.totalExpectedSales) as sellnums,sum(apd.bucha) as buchas,sum(apd.amount) as zonges,sum(apd.hanshui) as hanshuis,sum(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoues from cg_ti as ap inner join cg_ti_list as apd on apd.ti_id=ap.id inner join pro_products as p on apd.product=p.id where ap.id=$aid group by apd.net_id ");
//echo '333';

       // echo Db::table("ti_apply")->getLastSql();die;
        //print_r($applynet);die;
        $this->assign("applynet", $applynet);
        $net_num = count($applynet);
        $this->assign("net_num", $net_num);
        $xiao = 0;
        for ($i = 0; $i < count($applynet); $i++) {
            $xiao += $applynet[$i]["xiaoshoues"];
        }
        $this->assign("xiao", $xiao);
        $applyde = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")      // 网点
            ->join("cg_system s", "apd.xt_id=s.id", "LEFT")  // 系统
            ->join("cg_jxs j", "apd.jxs_id=j.id", "LEFT")  // 经销商
           // ->join("pro_products p", "apd.product=p.id")
            ->join("pro_products p", "apd.product=p.id","LEFT")
            ->join("pro_sku sk", "apd.sku=sk.id","LEFT")  //
            ->join("pro_series ps", "apd.series=ps.id","LEFT")
            ->join("pro_category cat", "apd.category=cat.id","LEFT")  //
            ->join("pro_brands bra", "apd.brand=bra.id","LEFT")
            ->join("pro_price pp", "pp.pid=p.id")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->join("cg_paymethod cp", "apd.paymethod=cp.id")
           // ->join("cg_fijiru cf", "apd.project=cf.id") //此处导致产品数据为空 ，检查原因： 费用计入方案 new tpm 没有
//            ->join("cg_fijiruzd fj", "apd.jrbm=fj.id") //  apd.jrbm  检查原因：费用计入部门 new tpm 没有
//            ->join("department d", "fj.title=d.id")  // d.de_name, cf.title as jrfa,
            ->where(["ap.id" => $aid])
            ->order("apd.id")
            //->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as hexiao_time,apd.totalExpectedSales as sell_num,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.pizhunweishui as zonge,apd.pizhunhanshui as hanshui,apd.brief as beizhu,apd.head as fuzeren,cp.title as zffs,cf.title as jrfa,(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoue,apd.feiyongmiaoshu as remark,d.de_name,apd.shuilv,apd.isVAT as dikou,apd.zhejia,apd.status as tag")
            ->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as hexiao_time,apd.totalExpectedSales as sell_num,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.pizhunweishui as zonge,apd.pizhunhanshui as hanshui,apd.brief as beizhu,apd.head as fuzeren,cp.title as zffs,(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoue,apd.feiyongmiaoshu as remark,apd.shuilv,apd.isVAT as dikou,apd.zhejia,apd.status as tag")
            ->select();

//  zonge
        $applyde = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")      // 网点
            ->join("cg_system s", "apd.xt_id=s.id", "LEFT")  // 系统
            ->join("cg_jxs j", "apd.jxs_id=j.id", "LEFT")  // 经销商
            ->join("pro_products p", "apd.product=p.id","LEFT")
            ->join("pro_sku sk", "apd.sku=sk.id","LEFT")  //
            ->join("pro_series ps", "apd.series=ps.id","LEFT")
            ->join("pro_category cat", "apd.category=cat.id","LEFT")  //
            ->join("pro_brands bra", "apd.brand=bra.id","LEFT")
            ->join("pro_price pp", "pp.pid=apd.id","LEFT")  //
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->join("cg_paymethod cp", "apd.paymethod=cp.id")
            ->where(["ap.id" => $aid])
            ->order("apd.id")
            ->field("apd.yesSales,apd.pizhunweishui as zonge,apd.yjsjtrfy,apd.yujiroi, apd.totalBenchmarkSales,ap.sn as no,n.title as net,s.title as xitong,ps.series_name,p.pro_name,bra.brand_name,cat.category_name,sk.sku_name,j.title as jxs,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,apd.start as start_time,apd.end as end_time,apd.expCanTime as hexiao_time,apd.totalExpectedSales,apd.bucha,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.pizhunweishui as pifuzonge,apd.pizhunhanshui as hanshui,apd.feiyongmiaoshu as remark,apd.head as fuzeren,cp.title as zffs,apd.brief as  beizhu,apd.shuilv,apd.isVAT as dikou,apd.zhejia,apd.status as tag,apd.paymethod as zfid")
            ->select();
  //  ,apd.pizhunweishui as zonge

       // p($applyde);

        for ($i = 0; $i < count($applyde); $i++) {
            $applyde[$i]["start_time"] = date("Y-m-d", $applyde[$i]["start_time"]);
            $applyde[$i]["end_time"] = date("Y-m-d", $applyde[$i]["end_time"]);
            $applyde[$i]["hexiao_time"] = date("Y-m-d", $applyde[$i]["hexiao_time"]);
        }

        $this->assign("applyde", $applyde);
        $zong = Db::table("cg_ti_list")->where(["ti_id" => $aid])->field("sum(pizhunhanshui) as zongshu")->find();
        $this->assign("zong", $zong);

        $this->assign("aid", $aid);
        return $this->fetch();
    }

//取消处理
    public function quxiaochuli()
    {
        $request = Request::instance();


        $data = $request->post();
//p($data);
        if ($data) {
            $aid = $data["aid"];
            //print_r($data);exit;
            //获得单据中现存的单子
            $all = Db::table("cg_ti_list")->where(["ti_id" => $data['aid']])->select();
            $jishu = 0;
            $qx = [];
            $did = [];
            for ($i = 0; $i < count($data["did"]); $i++) {
                if (trim($data["quxiaoyuanyin"][$i])) {
                    $qx[] = ["id" => $data["did"][$i], "yuanyin" => $data["quxiaoyuanyin"][$i]];
                    $jishu++;
                    $did[] = $data["did"][$i];
                }
            }
            //print_r($qx);exit;
            if (!$jishu) {
                return json_encode(["msg" => "至少删除一条明细", "state" => 2]);
            }

            Db::startTrans();
            try {
                //原单
                $apply = Db::table("cg_ti")->where(["id" => $aid])->find();

                //生成单号

                $strnum = $this->produceSN();
                $addapply = $apply;
                unset($addapply["id"]);
                $addapply["sn"] = $strnum;
                $addapply["ctime"] = time();
                $addapply["ptime"] = time();
                $addapply["old"] = $aid;
                $addapply["status"] = 1;
                $addapply["attach"] = $data["attach"];
                $addapply["cate_id"] = 3;
                $addapply["cuser"] = Session::get("employee_id");
                $addapply["puser"] = Session::get("employee_id");
                //print_r($addapply);exit;
                $res1 = Db::table("cg_ti")->insertGetId($addapply);
                $removedata = [];
                for ($i = 0; $i < count($all); $i++) {
                    for ($j = 0; $j < count($qx); $j++) {
                        //echo $all[$i]["id"]."---".$qx[$j]["id"]."|";
                        if ($all[$i]["id"] == $qx[$j]["id"]) {
                            $tmp = $all[$i];
                            $tmp["refer_id"] = $tmp["id"];
                            $tmp["cancel_reason"] = $qx[$j]["yuanyin"];
                            $tmp["ctime"] = time();
                            $tmp["ptime"] = time();
                            $tmp["cuser"] = Session::get("employee_id");
                            $tmp["puser"] = Session::get("employee_id");
                            $tmp["ti_id"] = $res1;
                            $tmp["status"] = 2;
                            unset($tmp["id"]);
                            $removedata[] = $tmp;
                            //echo 1;
                        }
                    }
                }
                //print_r($removedata);exit;
                //插入新明细
                $res2 = Db::table("cg_ti_list")->insertAll($removedata);
                //原明细
                $applymx = Db::table("cg_ti_list")->where(["ti_id" => $aid])->select();
                Db::table("cg_ti")->where(["id" => $aid])->update(["is_ydqx"=>1]);
                $savetype = $data["state"];

                if($data["state"]==3){
                    $flowId = db('cg_workflowset')->where(['id' => '22'])->value('flow_id');
                    $datawf = [];
                    $datawf['accessToken'] = session('accessToken');
                    $datawf['flowId'] = $flowId;
                    $datawf = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf', $datawf);
                    $insert = [];
                    $insert['ywlx'] = 22;
                    $row = db('cg_ti')->where('id', $res1)->field('title,sn')->find();
                    $insert['rwmcjbh'] = $row['title'] . '[' . $row['sn'] . ']';
                    $insert['yw_id'] = $res1;
                    $insert['status'] = 1;
                    $insert['department_id'] = db('department_employee')->where(['index' => 1, 'employee_id' => session('employee_id')])->value('department_id');
                    $insert['sqr_id'] = session('employee_id');
                    $insert['workId'] = $datawf->workId;
                    $insert['trackId'] = $datawf->flowNode->trackId;
                    db('cg_workflow')->insert($insert);
                    db('cg_ti')->where('id', $res1)->update(["status"=>3]);
                }
            } catch (\Exception $e) {
                //echo $e->getMessage();
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
            if ($res1 && $res2) {

                Db::commit();


                return json_encode(["msg" => "", "state" => 1]);
            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }

        } else {
            return json_encode(["msg" => "请正确提交", "state" => 2]);
        }
    }

    //系统反馈 xitongfankui
    public function wangdianfankui($aid,$feedbacktype)
    {
        //echo $aid.'a'.$feedbacktype;die;
        $this->assign("feedbacktype", $feedbacktype);
        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti next", "ap.new=next.id", "LEFT")
            ->join("ti_state s", "ap.status=s.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("job_employee je", "ec.id=je.employee_id", "LEFT")
            ->join("job j", "je.job_id=j.id", "LEFT")
            ->join("department_employee de", "ec.id=de.employee_id", "LEFT")
            ->join("department d", "de.department_id=d.id", "LEFT")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("cg_market_zoning jz", "jx.zoning=jz.id", "LEFT")
            ->join("cg_market_provice jp", "jx.provice=jp.id", "LEFT")
            ->join("cg_market_city jc", "jx.city=jc.id", "LEFT")
            ->where(["ap.id" => $aid, "de.index" => 1])
            ->field("ap.title,ap.sn as no,yuan.sn as yuanno,next.sn as nextno,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.ctime,jx.title as jingxiao,jz.title as fenqu,jp.title as sheng,jc.title as shi,ap.fb as is_fankui")
            ->find();
        $apply["created_on"] = date("Y-m-d", $apply["ctime"]);
        $this->assign("apply", $apply);
        $this->assign("aid", $aid);
        $em = Db::table("employee")->where(["id" => Session::get("employee_id")])->find();
        $this->assign("em", $em);
        $apde = Db::table("cg_ti_list")->query("select apd.ctime,apd.productlat as cp_type from cg_ti_list as apd   where apd.ti_id=$aid group by apd.ctime");
        //  $apde 有问题

        Db::startTrans();
        try {

        if($feedbacktype==1){
            //p($apde);
            foreach ($apde as $k=>&$v){
                $ctime=$v['ctime'];
                switch ($v['cp_type']){
                    case 1:
                        /*$apde2 = Db::table("cg_ti_list")->query("
                select apd.net_id,apd.id,n.title as net_name,pro. brand_name as proname,apd.productlat
                from cg_ti_list as apd
                inner join cg_net as n on apd.net_id=n.id

                inner join pro_brands as pro on apd.brand=pro.id
                where apd.ti_id=$aid and apd.ctime=$ctime
                group by  apd.net_id,apd.brand");*/
                        $v['data'] = Db::table("cg_ti_list")->query("
            select apd.net_id,apd.id,n.title as net_name,pro.brand_name as proname,pro.id as pro_id,apd.productlat,apd.yesSales,count('apd.id') as num,apd.yjsjtrfy
            from cg_ti_list as apd  
            inner join cg_net as n on apd.net_id=n.id 
            inner join pro_brands as pro on apd.brand=pro.id 
            where apd.ti_id=$aid and apd.ctime=$ctime  
            group by  apd.net_id,apd.brand");
                        // p($apde2);

                        $v['cp_type']='品牌';
                        break;
                    case 2:
                        //category_name 代替 brand_name
                        $v['data'] = Db::table("cg_ti_list")->query("
            select apd.net_id,apd.id,n.title as net_name,pro. category_name as proname,pro.id as pro_id,apd.productlat,apd.yesSales,count('apd.id') as num,apd.yjsjtrfy 
            from cg_ti_list as apd  
            inner join cg_net as n on apd.net_id=n.id 
            inner join pro_category as pro on apd.category=pro.id   //pro_category 代替 pro_brands    category 代替 brand
            where apd.ti_id=$aid and apd.ctime=$ctime  
            group by  apd.net_id,apd.category");  // category  代替 brand
                        $v['cp_type']='品类';
                        break;
                    case 3:
                        //echo '3';
                        $v['data'] = Db::table("cg_ti_list")->query("
            select apd.net_id,apd.id,n.title as net_name,pro. series_name as proname,pro.id as pro_id,apd.productlat,apd.yesSales,count('apd.id') as num,apd.yjsjtrfy  
            from cg_ti_list as apd  
            inner join cg_net as n on apd.net_id=n.id 
            inner join pro_series as pro on apd.series=pro.id 
            where apd.ti_id=$aid and apd.ctime=$ctime  
            group by  apd.net_id,apd.series");
                        $v['cp_type']='系列';
                        //echo 'e';die;
                        break;
                    case 4:
                        $v['data'] = Db::table("cg_ti_list")->query("
            select apd.net_id,apd.id,n.title as net_name,pro. sku_name as proname,pro.id as pro_id,apd.productlat,apd.yesSales,count('apd.id') as num,apd.yjsjtrfy
            from cg_ti_list as apd  
            inner join cg_net as n on apd.net_id=n.id 
            inner join pro_sku as pro on apd.sku=pro.id 
            where apd.ti_id=$aid and apd.ctime=$ctime  
            group by  apd.net_id,apd.sku");

                        $v['cp_type']='SKU';
                        break;
                    case 5:
                        //echo 'w';
                        $v['data'] = Db::table("cg_ti_list")->query("
            select apd.net_id,apd.id,n.title as net_name,pro. pro_name as proname,pro.id as pro_id,apd.productlat,apd.yesSales,count('apd.id') as num,apd.yjsjtrfy
            from cg_ti_list as apd  
            inner join cg_net as n on apd.net_id=n.id 
            inner join pro_products as pro on apd.product=pro.id 
            where apd.ti_id=$aid and apd.ctime=$ctime  
            group by  apd.net_id,apd.product");
                       // echo 's';die;
                        $v['cp_type']='单品';
                        break;

                }
//$v2 brand
            }

        }else{
            /*echo 'ee';
            echo $feedbacktype;die;*/
            foreach ($apde as $k=>&$v){
                $ctime=$v['ctime'];
                //echo $v['cp_type'];die;
                switch ($v['cp_type']){
                    case 1:
                        $v['data'] = Db::table("cg_ti_list")->query("
            select apd.xt_id,apd.id,n.title as net_name,pro.brand_name as proname,pro.id as pro_id,apd.productlat,apd.yesSales,count('apd.id') as num,apd.yjsjtrfy
            from cg_ti_list as apd  
            inner join cg_system as n on apd.xt_id=n.id 
            inner join pro_brands as pro on apd.brand=pro.id 
            where apd.ti_id=$aid and apd.ctime=$ctime  
            group by  apd.xt_id,apd.brand");

                        $v['cp_type']='品牌';
                        break;
                    case 2:
                        $v['data'] = Db::table("cg_ti_list")->query("
            select apd.xt_id,apd.id,n.title as net_name,pro. category_name as proname,pro.id as pro_id,apd.productlat,apd.yesSales,count('apd.id') as num,apd.yjsjtrfy 
            from cg_ti_list as apd  
            inner join cg_system as n on apd.xt_id=n.id 
            inner join pro_category as pro on apd.category=pro.id   
            where apd.ti_id=$aid and apd.ctime=$ctime  
            group by  apd.xt_id,apd.category");

                        $v['cp_type']='品类';
                        break;
                    case 3:
                        $v['data'] = Db::table("cg_ti_list")->query("
            select apd.xt_id,apd.id,n.title as net_name,pro. series_name as proname,pro.id as pro_id,apd.productlat ,apd.yesSales,count('apd.id') as num,apd.yjsjtrfy  //
            from cg_ti_list as apd  
            inner join cg_system as n on apd.xt_id=n.id 
            inner join pro_series as pro on apd.series=pro.id 
            where apd.ti_id=$aid and apd.ctime=$ctime  
            group by  apd.xt_id,apd.series");
                        $v['cp_type']='系列';
                        break;
                    case 4:
                        $v['data'] = Db::table("cg_ti_list")->query("
            select apd.xt_id,apd.id,n.title as net_name,pro. sku_name as proname,pro.id as pro_id,apd.productlat,apd.yesSales,count('apd.id') as num,apd.yjsjtrfy 
            from cg_ti_list as apd  
            inner join cg_system as n on apd.xt_id=n.id 
            inner join pro_sku as pro on apd.sku=pro.id 
            where apd.ti_id=$aid and apd.ctime=$ctime  
            group by  apd.xt_id,apd.sku");

                        $v['cp_type']='SKU';
                        break;
                    case 5:
                        $v['data'] = Db::table("cg_ti_list")->query("
            select apd.xt_id,apd.id,n.title as net_name,pro. pro_name as proname,pro.id as pro_id,apd.productlat,apd.yesSales,count('apd.id') as num,apd.yjsjtrfy 
            from cg_ti_list as apd  
            inner join cg_system as n on apd.xt_id=n.id 
            inner join pro_products as pro on apd.product=pro.id 
            where apd.ti_id=$aid and apd.ctime=$ctime  
            group by  apd.xt_id,apd.product");
                        $v['cp_type']='单品';
                        break;

                }
            }
        }

        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollBack();die;
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
    // jishu

        $wdfk=[[]];
        $j=0;
//p($apde);
        Db::startTrans();
        try {
            foreach ($apde as $k=>$v){
                $num=count($v['data']);
                foreach ($v['data'] as $k2=>$v2){

                    if($feedbacktype==1){
                        // echo 'q';
                        $wdfk[$j]['net_id']=$v2['net_id'];
                        //echo 'r';
                    }else{
                        $wdfk[$j]['net_id']=$v2['xt_id'];
                    }

                    $wdfk[$j]['id']=$v2['id'];
                    $wdfk[$j]['net_name']=$v2['net_name'];
                    $wdfk[$j]['proname']=$v2['proname'];
                    $wdfk[$j]['productlat']=$v2['productlat'];
                    $wdfk[$j]['yesSales']=$v2['yesSales'];
                    $wdfk[$j]['yjsjtrfy']=$v2['yjsjtrfy'];
                    $wdfk[$j]['pro_id']=$v2['pro_id'];
                    $wdfk[$j]['yesSale']=round($v2['yesSales']/$num, 2);  //未定义索引：yesSales

                    $wdfk[$j]['cp_type']=$v['cp_type'];
                    $j++;
                }
            }
        } catch (\Exception $e) {
            echo $e->getMessage();die;
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }

        foreach ($apde as $k=>$v){
            $num=count($v['data']);
            foreach ($v['data'] as $k2=>$v2){

                if($feedbacktype==1){
                    $wdfk[$j]['net_id']=$v2['net_id'];
                }else{
                    $wdfk[$j]['net_id']=$v2['xt_id'];
                }

                $wdfk[$j]['id']=$v2['id'];
                $wdfk[$j]['net_name']=$v2['net_name'];
                $wdfk[$j]['proname']=$v2['proname'];
                $wdfk[$j]['productlat']=$v2['productlat'];
                $wdfk[$j]['yesSales']=$v2['yesSales'];
                $wdfk[$j]['yjsjtrfy']=$v2['yjsjtrfy'];
                $wdfk[$j]['pro_id']=$v2['pro_id'];
                $wdfk[$j]['yesSale']=round($v2['yesSales']/$num, 2);

                $wdfk[$j]['cp_type']=$v['cp_type'];
                $j++;
            }
        }
        $this->assign("wdfk", $wdfk);
        return $this->fetch();
    }


    //整单反馈
    public function allfankui($aid)
    {
        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti next", "ap.new=next.id", "LEFT")
            ->join("ti_state s", "ap.status=s.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("job_employee je", "ec.id=je.employee_id", "LEFT")
            ->join("job j", "je.job_id=j.id", "LEFT")
            ->join("department_employee de", "ec.id=de.employee_id", "LEFT")
            ->join("department d", "de.department_id=d.id", "LEFT")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("cg_market_zoning jz", "jx.zoning=jz.id", "LEFT")
            ->join("cg_market_provice jp", "jx.provice=jp.id", "LEFT")
            ->join("cg_market_city jc", "jx.city=jc.id", "LEFT")
            ->where(["ap.id" => $aid, "de.index" => 1])
            ->field("ap.title,ap.sn as no,yuan.sn as yuanno,next.sn as nextno,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.ctime,jx.title as jingxiao,jz.title as fenqu,jp.title as sheng,jc.title as shi,ap.fb as is_fankui")
            ->find();
        //p($apply);
        //echo '1';  nums
        $apply["created_on"] = date("Y-m-d", $apply["ctime"]);
        $this->assign("apply", $apply);
        $em = Db::table("employee")->where(["id" => Session::get("employee_id")])->find();
        $this->assign("em", $em);
        $applyde = Db::table("cg_ti_list")->query("select sum(boxnum) as nums,sum(fb_boxnum) as fans,totalBenchmarkSales as  yesSalesas,ti_id from cg_ti_list where ti_id=$aid group by ctime");

        $apde["nums"] = round($applyde[0]["nums"], 2);
        if ($apply["is_fankui"]) {
            $apde["fans"] = round($applyde[0]["fans"], 2);

        } else {
            $apde["fans"] = $apde["nums"];

        }
        $apde["yesSales"] =0;
        foreach($applyde as $k=>$v){
            $apde["yesSales"] += $v['yesSalesas'];  // yesSalesas
        }

        $this->assign("apde", $apde);
        $sql4="select sum(boxnum) as nums,sum(fb_boxnum) as fans,totalBenchmarkSales as  yesSalesas,ti_id from cg_ti_list where ti_id=$aid group by ctime";

        $sql3="select d1.feetype as feiyong_id,sum(d1.pizhunhanshui) as hanshui,sum(d1.pizhunweishui) as weishui,amount,sum(d1.fb_shijiweishui) as shijijin,f3.title as kemu3,
                (select count(DISTINCT jxs_id) 
               from cg_ti_list as d2 
               where d2.ti_id=$aid and d2.feetype=d1.feetype ) as jxs_num,
                (select count(DISTINCT d3.cp_id) 
                from cg_ti_list as d3 where d3.ti_id=$aid and d3.feetype=d1.feetype) as pro_num from cg_ti_list as d1 
               inner join cg_feiyongkemu3 as f3 on d1.feetype=f3.id where d1.ti_id=$aid group by d1.feetype";

        $sql="select d1.feetype as feiyong_id,sum(d1.pizhunhanshui) as hanshui,sum(d1.pizhunweishui) as weishui,amount,sum(d1.fb_shijiweishui) as shijijin,f3.title as kemu3,
                (select count(DISTINCT jxs_id) 
               from cg_ti_list as d2 
               where d2.ti_id=$aid  and d2.feetype=d1.feetype and d2.ctime=d1.ctime) as jxs_num,
               (select count(DISTINCT xt_id) 
               from cg_ti_list as d2 
               where d2.ti_id=$aid and d2.feetype=d1.feetype and d2.ctime=d1.ctime) as xt_num,
               (select count(DISTINCT net_id) 
               from cg_ti_list as d2 
               where d2.ti_id=$aid and d2.feetype=d1.feetype and d2.ctime=d1.ctime) as net_num,
                (select count(DISTINCT d3.brand) 
                from cg_ti_list as d3 where d3.ti_id=$aid  and d3.feetype=d1.feetype and d3.ctime=d1.ctime) as brand_num, 
                (select count(DISTINCT d3.category) 
                from cg_ti_list as d3 where d3.ti_id=$aid  and d3.feetype=d1.feetype and d3.ctime=d1.ctime) as cat_num, 
                (select count(DISTINCT d3.series) 
                from cg_ti_list as d3 where d3.ti_id=$aid  and d3.feetype=d1.feetype and d3.ctime=d1.ctime) as ser_num,
                (select count(DISTINCT d3.sku) 
                from cg_ti_list as d3 where d3.ti_id=$aid  and d3.feetype=d1.feetype and d3.ctime=d1.ctime) as sku_num, 
                (select count(DISTINCT d3.product) 
                from cg_ti_list as d3 where d3.ti_id=$aid  and d3.feetype=d1.feetype and d3.ctime=d1.ctime) as pro_num
                from cg_ti_list as d1 
               inner join cg_feiyongkemu3 as f3 on d1.feetype=f3.id where d1.ti_id=$aid group by d1.feetype,d1.ctime"; // group by d3.ctime ,d1.ctime
        $aplist = Db::table("cg_ti_list")
            ->query($sql);

        $sqll= "select  count(jxs_id) as jxs_num,count(xt_id) as xt_num,count(net_id) as net_num ,count(brand) as brand_num,count(category) as cat_num,count(series) as ser_num
    ,count(sku) as sku_num,count(product) as pro_num
              from cg_ti_list where ti_id=$aid"; //  count  sum
        $aplists = Db::table("cg_ti_list")
            ->query($sqll);
        $aplists['0']['num']=1;//合计后面占多少列，至少有系统
        if(!empty($aplists['0']['num']))
            $aplists['0']['num']++;
        if(!empty($aplists['0']['xt_num']))
            $aplists['0']['num']++;
        if(!empty($aplists['0']['net_num']))
            $aplists['0']['num']++;
        if(!empty($aplists['0']['brand_num']))
            $aplists['0']['num']++;
        if(!empty($aplists['0']['cat_num']))
            $aplists['0']['num']++;
        if(!empty($aplists['0']['ser_num']))
            $aplists['0']['num']++;
        if(!empty($aplists['0']['sku_num']))
            $aplists['0']['num']++;
        if(!empty($aplists['0']['pro_num']))
            $aplists['0']['num']++;


        $this->assign("aplists", $aplists['0']);

        for ($i = 0; $i < count($aplist); $i++) {
            $aplist[$i]["jxs_num"] = round($aplist[$i]["jxs_num"], 2);
            $aplist[$i]["pro_num"] = round($aplist[$i]["pro_num"], 2);
            $aplist[$i]["hanshui"] = round($aplist[$i]["hanshui"], 2);

            $aplist[$i]["amount"] = round($aplist[$i]["amount"], 2);
            $aplist[$i]["weishui"] = round($aplist[$i]["amount"]/(1+0.06), 2);

            if ($apply["is_fankui"]) {
                $aplist[$i]["shijijin"] = round($aplist[$i]["shijijin"], 2);
            } else {
                $aplist[$i]["shijijin"] = $aplist[$i]["weishui"];
            }
        }
        $this->assign("aplist", $aplist);
        $this->assign("aid", $aid);
        return $this->fetch();  // totalBenchmarkSales  yesSales net_num
    }
     //查看流程图
    public function workflowchart()
    {
        $id = $this->request->param('id');
       
        $ywid=24;
       

        $workId = db('cg_workflow')->where(['ywlx' => $ywid, 'yw_id' => $id])->value('workId');

        $trackId = db('cg_workflow')->where(['ywlx' => $ywid, 'yw_id' => $id])->value('trackId');
        //$arr=$workId = db('cg_workflow')->where(['ywlx' => $ywid, 'yw_id' => $id])->find();
        //print_r($arr);exit;
        header('location:http://61.129.51.183:10010/hzwf73/workflow/module/workflow/flowchart.jsp?workId=' . $workId .
            '&trackId=' . $trackId);
    }


    //删除明细
    public function shanchu()
    {
        $request = Request::instance();
        $data = $request->post();
        $did = $data["did"];
        $ctime = $data["ctime"];
        Db::startTrans();
        try {
            $res1 = Db::table("cg_ti_list")->where("ti_id in($did)  and ctime=$ctime")->delete();
        } catch (\Exception $e) {
            //echo $e->getMessage();
            Db::rollBack();
            return 2;
        }
        if ($res1) {
            Db::commit();
            return 1;
        } else {
            Db::rollBack();
            return 2;
        }
    }

    //修改明细
    public function xiugai2($did)
    {
        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);

        //费用计入方案
        $fipay = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fijiru', $fipay);

        //获取优惠费用类型
        $where['esuseway'] = ['like', '%"9"%'];
        // $where["tejiabuchatype"] = 10;
        $youhui = db("cg_feiyongkemu3")->where($where)->select();

        $this->assign("youhui", $youhui);


        $this->assign("did", $did);
        $detail = Db::table("cg_ti_list")->alias("apd")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("pro_products p", "apd.product=p.id")
            ->join("pro_price pp", "pp.pid=p.id")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->join("cg_paymethod cp", "apd.paymethod=cp.id")
            ->join("cg_fijiru cf", "apd.project=cf.id")
            ->join("cg_fijiruzd fj", "apd.jrbm=fj.id")->join("department d", "fj.title=d.id")
            ->where(["apd.id" => $did])
            ->field("apd.start as start_time,apd.end as end_time,apd.expCanTime as hexiao_time,apd.head as fuzeren,apd.zhejia,apd.amount as zonge,apd.paymethod as zfid,apd.project as fyfa,apd.brief as beizhu,p.unit,pp.factory,apd.boxnum as sell_num,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.wangdian_yuan,apd.wangdian_zhejia,apd.wangdianmaoli,apd.bucha,apd.lingshou_price,apd.huodong_price,apd.maoli,apd.feiyongmiaoshu as remark,f3.title as zftitle,d.de_name,fj.id as jrbmid,apd.net_id,n.title as netname,apd.product as pro_id,p.pro_name,apd.feetype as feiyong_id,p.box_num,apd.jxs_id,pp.retail_low,pp.retail_high,pp.promotion_high,pp.promotion_low,apd.netout,apd.huodongout")
            ->find();
        $detail["start_time"] = date("Y/m/d", $detail["start_time"]);
        $detail["end_time"] = date("Y/m/d", $detail["end_time"]);
        $detail["hexiao_time"] = date("Y/m/d", $detail["hexiao_time"]);
        $this->assign("detail", $detail);
        return $this->fetch();
    }

    //修改明细   $cp_name
    public function xiugai($did)
    {
        $request = Request::instance();
        $data = $request->get();
        // expCanTime
        $aid = $data["aid"];
        $ctime = $data["ctime"];
        //echo '333';
        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->where("ap.id=$aid and apd.ctime=$ctime ")
            ->field(" apd.ctime,ap.id,apd.start,apd.end,apd.brief,apd.cp_type,noSales,yesSales,feiyonglv,roi,expCanTime,start,end,ysstart,ysend,is_shejixiaoliang,noSales,yesSales,yjSalesType,sum(hanshui) as hanshui,apd.khtype")
            ->group('apd.ctime')
            ->find();
        //p($apply);

        /*$hbxx=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->where("ap.id=$aid and apd.ctime=$ctime ")
            ->field(" apd.ctime,ap.id,apd.start,apd.end,apd.brief,apd.cp_type,noSales,yesSales,feiyonglv,roi,expCanTime,start,end,ysstart,ysend,is_shejixiaoliang,noSales,yesSales,yjSalesType,sum(hanshui) as hanshui,apd.khtype")
            ->group('apd.ctime')
            ->find();*/
       // p($apply);
        $apply['zl']=$apply['yesSales']-$apply['noSales'];
        $apply['expCanTime'] = date('Y-m-d',$apply['expCanTime']);
        $apply['start'] = date('Y-m-d',$apply['start']);
        $apply['end'] = date('Y-m-d',$apply['end']);
        $apply['ysstart'] = date('Y-m-d',$apply['ysstart']);
        $apply['ysend'] = date('Y-m-d',$apply['ysend']);
        //p($apply);
        $cp_type=$apply['cp_type'];
        $id=$apply['id'];

        //echo $cp_type;die;
        Db::startTrans();
        try {
        switch ($cp_type){
            case 0:
                $cp_type='brand';
                $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand as pro_name,category,series,sku,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids,cp_sm,cp_zb  from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime  group by $cp_type");
                $cptype='品牌';
                $cp_name=array();
                /*echo '3';
                p($a);*/
                foreach ($a as $av=>$ak){
                    $cp=Db::name('pro_brands')->where(['id'=>$ak['pro_name']])->field('brand_name name')->find();
                    $cp_name[$av]['id']=$ak['pro_name'];
                    $cp_name[$av]['name']=$cp['name'];
                    $cp_name[$av]['cp_sm']=$ak['cp_sm'];
                    $cp_name[$av]['cp_zb']=$ak['cp_zb'];
                }
                break;
            case 1:
                $cp_type='category';
                $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category  as pro_name,series,sku,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids,cp_sm,cp_zb   from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                $cptype='品类';
                $cp_name=array();
                foreach ($a as $av=>$ak){
                    $cp=Db::name('pro_category')->where(['id'=>$ak['pro_name']])->field('category_name name')->find();
                    $cp_name[$av]['id']=$ak['pro_name'];
                    $cp_name[$av]['name']=$cp['name'];
                    $cp_name[$av]['cp_sm']=$ak['cp_sm'];
                    $cp_name[$av]['cp_zb']=$ak['cp_zb'];
                }
                break;
            case 2:
                $cp_type='series';
                $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category,series  as pro_name,sku,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids,cp_sm,cp_zb   from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                $cptype='系列';
                $cp_name=array();
                foreach ($a as $av=>$ak){
                    $cp=Db::name('pro_series')->where(['id'=>$ak['pro_name']])->field('series_name name')->find();
                    $cp_name[$av]['id']=$ak['pro_name'];
                    $cp_name[$av]['name']=$cp['name'];
                    $cp_name[$av]['cp_sm']=$ak['cp_sm'];
                    $cp_name[$av]['cp_zb']=$ak['cp_zb'];
                }
                break;
            case 3:
                $cp_type='sku';
                $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category,series,sku  as pro_name,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids,cp_sm,cp_zb   from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                /*echo '3';
                p($a);*/
                $cptype='SKU';
                $cp_name=array();
                foreach ($a as $av=>$ak){
                    $cp=Db::name('pro_sku')->where(['id'=>$ak['pro_name']])->field('sku_name name')->find();
                    $cp_name[$av]['id']=$ak['pro_name'];
                    $cp_name[$av]['name']=$cp['name'];
                    $cp_name[$av]['cp_sm']=$ak['cp_sm'];
                    $cp_name[$av]['cp_zb']=$ak['cp_zb'];
                }
                break;
            case 4:
                $cp_type='product';
                //echo 'eee';die;
                //$a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category,series,sku,product as pro_name,sum(net_id) as net_ids,sum(xt_id) as xt_ids,cp_sm,cp_zb    from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,now_price,yuan_price,zhejia,jizhunboxnum,fylx,product as pro_name,sum(net_id) as net_ids,sum(xt_id) as xt_ids,cp_sm,cp_zb,jizhunboxnum as boxnum,lingshou_price,huodong_price,wangdian_zhejia,wangdian_yuan,wangdian_price    from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");

                //dump($a);  //boxnum   ,p.lingshou_price,huodong_price
                //p($a);
                $cptype='单品';
                $cp_name=array();
                foreach ($a as $av=>$ak){

                    $cp = Db::name("pro_products")->alias("p")
                        ->join("pro_price pp", "pp.pid=p.id") //pro_price
                        //->field('p.pro_name as name,p.unit,p.box_num,pp.box_retail_standard as xtxgj')
                        ->field('p.pro_name as name,p.unit,p.box_num,pp.box_retail_standard as xtxgj')
                        ->where(['p.id'=>$ak['pro_name']])
                        ->find();
                    $cp_name[$av]['id']=$ak['pro_name'];
                    $cp_name[$av]['name']=$cp['name'];
                    $cp_name[$av]['unit']=$cp['unit'];
                    $cp_name[$av]['box_num']=$cp['box_num'];
                    $cp_name[$av]['xtxgj']=$cp['xtxgj'];
                    $cp_name[$av]['lingshou_price']=$ak['lingshou_price'];
                    $cp_name[$av]['huodong_price']=$ak['huodong_price'];
                    $cp_name[$av]['boxnum']=$ak['boxnum'];
                    $cp_name[$av]['wangdian_yuan']=$ak['wangdian_yuan'];
                    $cp_name[$av]['wangdian_price']=$ak['wangdian_price'];
                    $cp_name[$av]['wangdian_zhejia']=$ak['wangdian_zhejia'];
                    $cp_name[$av]['cp_sm']=$ak['cp_sm'];
                    $cp_name[$av]['cp_zb']=$ak['cp_zb'];
                    $cp_name[$av]['now_price']=$ak['now_price'];
                    $cp_name[$av]['yuan_price']=$ak['yuan_price'];
                    $cp_name[$av]['zhejia']=$ak['zhejia'];
                    $cp_name[$av]['jizhunboxnum']=$ak['jizhunboxnum'];
                    $cp_name[$av]['fylx']=$ak['fylx'];

                    if($cp_name[$av]['wangdian_price']>0){
                        $cp_name[$av]['sj2']=round(100*($cp_name[$av]['huodong_price']-$cp_name[$av]['wangdian_price'])/$cp_name[$av]['wangdian_price'], 2);
                        //echo $cp_name[$av]['lingshou_price'].'-'.$cp_name[$av]['wangdian_price'];die;
                    }else {
                        $cp_name[$av]['sj2']='';
                    }
                    if($cp_name[$av]['huodong_price']>0){
                        $cp_name[$av]['dk2']=round(100*($cp_name[$av]['huodong_price']-$cp_name[$av]['wangdian_price'])/$cp_name[$av]['huodong_price'], 2);
                    }else {
                        $cp_name[$av]['dk2']='';
                    } // now_price xtxgj

                    if($cp_name[$av]['now_price']>0){
                        $cp_name[$av]['sj']=round(100*($cp_name[$av]['xtxgj']-$cp_name[$av]['now_price'])/$cp_name[$av]['now_price'], 2);
                    }else {
                        $cp_name[$av]['sj']='';
                    }
                    if($cp_name[$av]['xtxgj']>0){
                        $cp_name[$av]['dk']=round(100*($cp_name[$av]['now_price']-$cp_name[$av]['xtxgj'])/$cp_name[$av]['xtxgj'], 2);
                    }else {
                        $cp_name[$av]['dk']='';
                    }
                }
                break;

        }//cp_sm
        } catch (\Exception $e) {
            // echo $e->getMessage();
            Db::rollBack();die;
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
        //p($cp_name);
        if(isset($cp_name['0']['fylx'])){
            $fylx=$cp_name['0']['fylx'];
        }else{
            $fylx=1;
        }

        $this->assign("fylx",$fylx);
       // p($cp_name);
        $this->assign('cp_name',json_encode($cp_name));
        $this->assign("apply", $apply);

       //客户详情
        $khxt = Db::table("cg_ti_list")->query("select xt_id,xt_zb,net_num,sys.title  from  cg_ti_list as apd inner join cg_system as sys on apd.xt_id=sys.id where apd.ti_id=$id and apd.ctime=$ctime   group by apd.xt_id ");
       // p($khxt);
        //p($apply);
        $this->assign('khxt',json_encode($khxt));
        $khnet = Db::table("cg_ti_list")->query("select net_id,xt_zb,net_num,sys.title  from  cg_ti_list as apd inner join cg_system as sys on apd.xt_id=sys.id where apd.ti_id=$id and apd.ctime=$ctime   group by apd.net_id ");
        $khnet =Db::table("cg_ti_list")->query("
                                select apd.net_id,net.title
                                from  cg_ti_list as apd 
                                inner join cg_net as net on apd.net_id=net.id 
                                where apd.ti_id=$id and apd.ctime=$ctime   
                                group by apd.net_id ");

        //$this->assign('khnet',json_encode($khxt));
        $this->assign('khnet',json_encode($khnet));
        //p($khnet);

        //费用说明
        $sql="select apd.feetype,apd.fylx,apd.productlat,fy.title,apd.payee,apd.payeetype,apd.paymethod,pay.title as payname,pay.method,apd.feiyongmiaoshu,apd.amount,apd.cl_type,apd.cl_place,apd.cl_size,sum(apd.hanshui) as hanshuis,apd.brief,apd.feiyongmiaoshu
                                 from  cg_ti_list as apd 
                                 inner join cg_feiyongkemu3 as fy on apd.feetype=fy.id
                                 inner join cg_paymethod as pay on apd.paymethod=pay.id  
                                 where  apd.ctime=$ctime  and apd.ti_id=$id
                                 group by apd.feetype"; //anp
// payname paymethod
        $fee = Db::table("cg_ti_list")->query($sql);
        //dump($fee);

        foreach ($fee as $k =>&$v){
            if ($v['payeetype']==2){
                $v['payeename']=Db::name('gys')->where('id',$v['payee'])->value('gys_name');
            }
            $cl_type = [
                ['title'=>'货架陈列','id'=>'1'],
                ['title'=>'堆头陈列','id'=>'2'],
                ['title'=>'端架陈列','id'=>'3'],
                ['title'=>'包柱陈列','id'=>'4'],
                ['title'=>'挂网陈列','id'=>'5'],
                ['title'=>'其他陈列','id'=>'6'],
            ];
            $cl_place = [
                ['title'=>'主通道','id'=>'1'],
                ['title'=>'副通道','id'=>'2'],
                ['title'=>'收银台','id'=>'3'],
                ['title'=>'卖场门口','id'=>'4'],
                ['title'=>'端架两侧','id'=>'5'],
                ['title'=>'其他位置','id'=>'6'],
            ];
            $cl_size =[
                ['title'=>'1m x 1m','id'=>'1'],
                ['title'=>'2m x 1m','id'=>'2'],
                ['title'=>'2m x 2m','id'=>'3'],
                ['title'=>'4m x 1m','id'=>'4'],
                ['title'=>'整节端架','id'=>'5'],
                ['title'=>'半节端架','id'=>'6'],
                ['title'=>'其他尺寸','id'=>'7'],
            ];
            $v['cl_typename']='';
            if(!empty($v['cl_type'])){
                foreach ($cl_type as $ck=>$cv){
                    if($v['cl_type']==$cv['id'])
                        $v['cl_typename']=$cv['title'];
                }
            }

            $v['cl_placename']='';
            if(!empty($v['cl_place'])){
                foreach ($cl_place as $ck=>$cv){
                    if($v['cl_place']==$cv['id'])
                        $v['cl_placename']=$cv['title'];
                }
            }

            $v['cl_sizename']='';
            if(!empty($v['cl_size'])){
                foreach ($cl_size as $ck=>$cv){
                    if($v['cl_size']==$cv['id'])
                        $v['cl_sizename']=$cv['title'];
                }
            }


        }

        $fylx=$fee['0']['fylx'];
        $this->assign('fylx',$fylx);
        //echo 'ert';die;
        //dump($fee); //ti_id

        foreach ($fee as $k =>&$v){
            $feetype=$v['feetype'];
            $sql="select * from  cg_ti_hb  where  ctime=$ctime  and ti_id=$id and fylx=$feetype";
            $hbxx = Db::table("cg_ti_hb")->query($sql);
          //  p($hbxx);
$v['hb']='';
            foreach ($hbxx as $hk=>$hv){
                if(!empty($v['hb'])){
                    // wlName:西部人纯葵花籽油1L,num:44,wlyptype:0;wlName:测试销售物料,num:55,wlyptype:1
                    $v['hb']=$v['hb'].';wlName:'.$hv['wlName'].',num:'.$hv['num'].',wlyptype:'.$hv['wlyptype'];
                }else{
                    $v['hb']='wlName:'.$hv['wlName'].',num:'.$hv['num'].',wlyptype:'.$hv['wlyptype'];
                }
            }


            //echo '$ctime:'.$ctime.':feetype:'.$feetype.';id:'.$id;
            $sql2="select cb_name,cb_zb from  cg_ti_list  where    ti_id=$id and feetype=$feetype and ctime=$ctime group by cb_name";
            $cb = Db::table("cg_ti")->query($sql2);
            /*echo 'yyy';
            dump($cb);*/

            $cbinfo='';

            $v['cbinfo']='';
            foreach ($cb as $hk=>$hv){
                if(!empty($v['cbinfo'])){  // 西北,40%;西南,60%
                    // wlName:西部人纯葵花籽油1L,num:44,wlyptype:0;wlName:测试销售物料,num:55,wlyptype:1
                    $v['cbinfo']=$v['cbinfo'].';'.$hv['cb_name'].','.$hv['cb_zb'].'%';
                }else{
                    $v['cbinfo']=$hv['cb_name'].','.$hv['cb_zb'].'%';
                }
            }
            //p($v);
            //hb 'hb'

          /*  $sql="select apd.feetype,apd.fylx,apd.productlat,fy.title,apd.payee,apd.payeetype,apd.paymethod,pay.title as payname,pay.method,apd.feiyongmiaoshu,apd.amount,apd.cl_type,apd.cl_place,apd.cl_size,sum(apd.hanshui) as hanshuis,apd.brief,apd.feiyongmiaoshu
                                 from  cg_ti_list as apd
                                 inner join cg_feiyongkemu3 as fy on apd.feetype=fy.id
                                 inner join cg_paymethod as pay on apd.paymethod=pay.id
                                 where  apd.ctime=$ctime  and apd.ti_id=$id
                                 group by apd.feetype"; //anp
// payname paymethod
            $fee = Db::table("cg_ti_list")->query($sql);*/


            //p($hbxx);
            if($hbxx){
                $v['hbtype']=1;
                $v['hbinfo']=$hbxx;

            }else{
                $v['hbtype']=2;
                $v['hbinfo']=[];
            }
            //echo Db::table("cg_ti_hb")->getLastSql();


        }
       // die;
        //p($fee);  //  cb_name


        $this->assign('fee',json_encode($fee));

        //p($c);
        $this->assign("aid", $aid);
        //以上新加的

        $jxsid = $this->request->get('jxsid') ;
        if(empty($jxsid)||$jxsid='undefined'){
            $jxsid=Db::name('cg_ti')->where('id',$aid)->value('jxs_id');
        }
        $id = $this->request->get('id');
        $channeltype   = Db::name('cg_jxs')->where('id',$jxsid)->value('channeltype');
        $title   = Db::name('cg_jxs')->alias('jxs')
            ->join("cg_market_city cit","jxs.city=cit.id")
            ->join("cg_market_provice pro","cit.provice=pro.id")
            ->join("cg_market_zoning zon","pro.zoning=zon.id")
            ->where('jxs.id',$jxsid)->value('zon.title');
        $titlename   = Db::name('cg_jxs')->alias('jxs')
            ->where('jxs.id',$jxsid)->value('jxs.title');
        $this->assign('titlename',$titlename); //选择的经销商
        $this->assign('title',$title);//成本中心 之前选择的经销商所对应的地区

        $this->assign('jxsid',$jxsid);
        $this->assign('id',$id);
        $this->assign('channeltype',$channeltype);
       //echo '9';die;
        return $this->fetch();
    }  //$fee
    //提交工作流  需修改
    public function gostate($aid, $state)
    {
        $data["id"] = $aid;
        $cate_id=db("cg_ti")->where(["id"=>$aid])->value("cate_id");
        $ys=$this->tiys($aid);
        if($ys===0)
            return json_encode(["msg" => "尚未设定ti预算格式无法提交", "state" => 2]);
        $data["status"] = $state;
        $data["ptime"] = time();
        $data["puser"] = Session::get("employee_id");
        Db::startTrans();
        try {

            $res1 = Db::table("cg_ti")->update($data);
            if($ys){
                Db::table("yusuan_detail")->insertAll($ys);
            }
            if($cate_id==1)
                $flowId = db('cg_workflowset')->where(['id' => '1'])->value('flow_id');
            else if($cate_id==2)
                $flowId = db('cg_workflowset')->where(['id' => '21'])->value('flow_id');
            else if($cate_id==3)
                $flowId = db('cg_workflowset')->where(['id' => '22'])->value('flow_id');
            $data = [];
            $data['accessToken'] = session('accessToken');
            $data['flowId'] = $flowId;
            $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf', $data);
            $insert = [];
            if($cate_id==1){
                $insert['ywlx'] = 3;
            }else if($cate_id==2){
                $insert['ywlx'] = 21;
            }else{
                $insert['ywlx'] = 22;
            }

            $row = db('cg_ti')->where('id', $aid)->field('title,sn')->find();
            $insert['rwmcjbh'] = $row['title'] . '[' . $row['sn'] . ']';
            $insert['yw_id'] = $aid;
            $insert['status'] = 1;
            $insert['department_id'] = db('department_employee')->where(['index' => 1, 'employee_id' => session('employee_id')])->value('department_id');
            $insert['sqr_id'] = session('employee_id');
            $insert['workId'] = $data->workId;
            $insert['trackId'] = $data->flowNode->trackId;
            db('cg_workflow')->insert($insert);

        } catch (\Exception $e) {
            //echo $e->getMessage();
            Db::rollBack();
            return json_encode(["msg" => $e->getMessage(), "state" => 2]);
        }
        if ($res1) {

            Db::commit();


            return json_encode(["msg" => "", "state" => 1]);
        } else {
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
    }

    public function shanchuap($aid)
    {
        Db::startTrans();
        try {
            //是否解锁原单
            $yuanid=db("cg_ti")->where(["id" => $aid])->value("old");
            if($yuanid){
                db("cg_ti")->where(["id"=>$yuanid])->update(["is_ydqx"=>0]);
            }
            $res1 = Db::table("cg_ti")->where(["id" => $aid])->delete();
            $res2 = Db::table("cg_ti_list")->where(["ti_id" => $aid])->delete();

            $ys=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("Y.type=1 and yd.aid=$aid")->field("yd.id")->select();

            if($ys){
                $ysarr=[];
                for($i=0;$i<count($ys);$i++){
                    $ysarr[]=$ys[$i]["id"];
                }
                $ysarr=implode(',',$ysarr);
                db("yusuan_detail")->where("id in($ysarr)")->delete();
            }

        } catch (\Exception $e) {
            //echo $e->getMessage();
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
        if ($res1) {

            Db::commit();


            return json_encode(["msg" => "", "state" => 1]);
        } else {
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
        }
    }

    public function produceSN()
    {
        //生成编号
        $max = db('cg_ti')->where('sn', 'like', date('Ymd') . '%')->max('sn'); //编号递增开始位置基础

        if ($max) {
            $max = (double)$max;
            $insert_sn = $max + 1;
        } else {
            $insert_sn = date('Ymd') . '0001';
        }
        return $insert_sn;
    }

    //生成反馈sn
    public function producefbSN()
    {
        //生成编号
        $max = db('all_ti_feeback_list')->where('no', 'like', date('Ymd') . '%')->max('no'); //编号递增开始位置基础

        if ($max) {
            $max = (double)$max;
            $insert_sn = $max + 1;
        } else {
            $insert_sn = date('Ymd') . '0001';
        }
        return $insert_sn;
    }

    //整单反馈操作
    public function alldanfankui2()
    {
        $request = Request::instance();
        $data = $request->post();
        if ($data) {
            $aid = $data["aid"];
            $strnum = $this->producefbSN(); //生成反馈sn
            $datalist = ["no" => $strnum, "type" => 0, "apply_id" => $aid, "c_user_id" => Session::get("employee_id"), "created_on" => date("Y-m-d H:i:s"), "state" => 1,
                "remark" => $data["remark"], "fujian" => $data["attach"]
            ];  //all_ti_feeback_list 数据
            //获取原单库存 没有销售箱数（boxnum），直接获取活动销售额（yesSales）
            //$applyde = Db::table("cg_ti_list")->query("select sum(boxnum) as nums from cg_ti_list where ti_id=$aid");
            $applyde = Db::table("cg_ti_list")->query("select yesSales from cg_ti_list where ti_id=$aid group by ctime");
            $yuannum=0;
            foreach ($applyde as $apk=>$apv){
                $yuannum=$yuannum+$apv['yesSales'];
            }
            //$applyde=$all;
            //dump($applyde);die;
            //$yuannum = $applyde[0]["nums"];
            $bili = $data["box_num"] / $yuannum;
            //echo $bili;
            echo '[]';die;
            $aplist = Db::table("cg_ti_list")->query("select d1.feetype as feiyong_id,sum(d1.pizhunweishui) as hanshui from cg_ti_list as d1  where d1.ti_id=$aid group by d1.feetype");
            // print_r($data);exit;
            $fbi = Db::table("all_ti_feeback_list")->where(["apply_id" => $aid, "is_deleted" => 0, "state" => 7])->count();

            //echo '3';die;
            if ($fbi)
                return json_encode(["msg" => "本申请存在已通过的反馈申请，不能使用整单反馈", "state" => 2]);
            Db::startTrans();
            try {
                echo '1';
                Db::table("all_ti_feeback_list")->where(["apply_id" => $aid])->update(["is_deleted" => 1]);
                echo '2';
                $res2 = Db::table("all_ti_feeback_list")->insertGetId($datalist);

                //所有实际销量按比例增加
                $res = Db::table("ti_apply_detail")->query("update cg_ti_list set fb_shijixiaoliang=totalExpectedSales*$bili,fb_boxnum=boxnum*$bili where ti_id=$aid");
                dump($res);
                //p($res);
                echo '34';die;
                //安费用纬度处理
                for ($i = 0; $i < count($data["feiyong_id"]); $i++) {
                    for ($j = 0; $j < count($aplist); $j++) {
                        if ($data["feiyong_id"][$i] == $aplist[$j]["feiyong_id"]) {
                            //计算比例
                            $bilishui = $data["fankuijine"][$i] / $aplist[$j]["hanshui"];
                            if (trim($data["shuilv"][$i]))
                                $shuilv = $data["shuilv"][$i];
                            else
                                $shuilv = 0;

                            $nowt = time();
                            $user = Session::get("employee_id");
                            //return json_encode(["msg"=>"update ti_apply_detail set fankuishuilv={$shuilv},fankuidikou={$data["is_di"][$i]},fankuijine=(pifzonge+pifuzonge*shuilv/100)*$bilishui/(1+{$shuilv}/100) where is_deleted=0 and apply_id=$aid and feiyong_id={$data["feiyong_id"][$i]}","state"=>2]);
                            //$is_di=
                            //a=b/(1+shui/100)
                            if($data["is_di"][$i]==1){
                                $res = Db::table("ti_apply_detail")->query("update cg_ti_list set fb_shuilv={$shuilv},fb_isVAT={$data["is_di"][$i]},fb_brief='{$data["remark"]}',fb_shijiweishui=(pizhunweishui*$bilishui),fb_time=$nowt,fb_hanshui=(pizhunweishui*$bilishui)*(1+{$shuilv}/100),fb_user=$user,hx_status=5,fb_shijitourufeiyong=(pizhunweishui*$bilishui) where ti_id=$aid and feetype={$data["feiyong_id"][$i]}");
                            }else{
                                $res = Db::table("ti_apply_detail")->query("update cg_ti_list set fb_shuilv={$shuilv},fb_isVAT={$data["is_di"][$i]},fb_brief='{$data["remark"]}',fb_shijiweishui=(pizhunweishui*$bilishui),fb_time=$nowt,fb_hanshui=(pizhunweishui*$bilishui)*(1+{$shuilv}/100),fb_user=$user,hx_status=5,fb_shijitourufeiyong=(pizhunweishui*$bilishui)*(1+{$shuilv}/100) where ti_id=$aid and feetype={$data["feiyong_id"][$i]}");
                            }



                        }
                    }
                }
                //return;
                $dataup = ["id" => $aid, "fb" => 1, "fd_id" => $res2];
                Db::table("cg_ti")->update($dataup);
            } catch (\Exception $e) {
                //echo $e->getMessage();
                Db::rollBack();
                return json_encode(["msg" => $e->getMessage(), "state" => 2]);
            }

            if ($res2) {
                if($data["state"]==3){
                    $jieguo=$this->gowork(17,$res2);
                    if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                        Db::commit();
                        return $jieguo;
                    }else{
                        Db::rollBack();
                        return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                    }
                }else{
                    Db::commit();
                    return json_encode(["msg" => "", "state" => 1]);
                }



            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
            //Db::commit();
        } else {
            return json_encode(["msg" => "请正确提交", "state" => 2]);
        }
    }


    //整单反馈操作
    public function alldanfankui()
    {
        $request = Request::instance();
        $data = $request->post();
        //p($data);
        if ($data) {
            $aid = $data["aid"];
            $strnum = $this->producefbSN();
            $datalist = ["no" => $strnum, "type" => 3, "apply_id" => $aid, "c_user_id" => Session::get("employee_id"), "created_on" => date("Y-m-d H:i:s"), "state" => 1,
                "remark" => $data["remark"], "fujian" => $data["attach"]
            ];
            //获取原单库存
            //$applyde = Db::table("cg_ti_list")->query("select sum(boxnum) as nums from cg_ti_list where ti_id=$aid");
            //$yuannum = $applyde[0]["nums"];
            $applyde = Db::table("cg_ti_list")->query("select totalExpectedSales from cg_ti_list where ti_id=$aid group by ctime");//  totalExpectedSales
            $yuannum=0;
            foreach ($applyde as $apk=>$apv){
                $yuannum=$yuannum+$apv['totalExpectedSales'];
            }
            if($yuannum!=0){
                $bili = $data["box_num"] / $yuannum;
            }else{
                $bili='';
            }
             //$data["box_num"] 总销量（由箱改为元）
            //$aplist = Db::table("cg_ti_list")->query("select d1.feetype as feiyong_id,sum(d1.pizhunweishui) as hanshui from cg_ti_list as d1  where d1.ti_id=$aid group by d1.feetype");
            $aplist = Db::table("cg_ti_list")->query("select d1.feetype as feiyong_id,sum(d1.hanshui) as hanshui from cg_ti_list as d1  where d1.ti_id=$aid group by d1.feetype");

            $fbi = Db::table("all_ti_feeback_list")->where(["apply_id" => $aid, "is_deleted" => 0, "state" => 7])->count();
            if ($fbi)
                return json_encode(["msg" => "本申请存在已通过的反馈申请，不能使用整单反馈", "state" => 2]);
            Db::startTrans();
            try {
                Db::table("all_ti_feeback_list")->where(["apply_id" => $aid])->update(["is_deleted" => 1]);
                $res2 = Db::table("all_ti_feeback_list")->insertGetId($datalist);

                //所有实际销量按比例增加  只有实际销量并无实际销售箱数
                //$res = Db::table("ti_apply_detail")->query("update cg_ti_list set fb_shijixiaoliang=totalExpectedSales*$bili,fb_boxnum=boxnum*$bili where ti_id=$aid");
                $res = Db::table("ti_apply_detail")->query("update cg_ti_list set fb_shijixiaoliang=totalExpectedSales*$bili where ti_id=$aid");
                //安费用纬度处理
                for ($i = 0; $i < count($data["feiyong_id"]); $i++) {
                    for ($j = 0; $j < count($aplist); $j++) {
                        if ($data["feiyong_id"][$i] == $aplist[$j]["feiyong_id"]) {
                            //计算比例
                            $bilishui = $data["fankuijine"][$i] / $aplist[$j]["hanshui"];
                            if (trim($data["shuilv"][$i]))
                                $shuilv = $data["shuilv"][$i];
                            else
                                $shuilv = 0;

                            $nowt = time();
                            $user = Session::get("employee_id");

                            if($data["is_di"][$i]==1){
                                $res = Db::table("ti_apply_detail")->query("update cg_ti_list set fb_shuilv={$shuilv},fb_isVAT={$data["is_di"][$i]},fb_brief='{$data["remark"]}',fb_shijiweishui=(hanshui*$bilishui),fb_time=$nowt,fb_hanshui=(hanshui*$bilishui)*(1+{$shuilv}/100),fb_user=$user,hx_status=5,fb_shijitourufeiyong=(hanshui*$bilishui) where ti_id=$aid and feetype={$data["feiyong_id"][$i]}");
                            }else{
                                $res = Db::table("ti_apply_detail")->query("update cg_ti_list set fb_shuilv={$shuilv},fb_isVAT={$data["is_di"][$i]},fb_brief='{$data["remark"]}',fb_shijiweishui=(hanshui*$bilishui),fb_time=$nowt,fb_hanshui=(hanshui*$bilishui)*(1+{$shuilv}/100),fb_user=$user,hx_status=5,fb_shijitourufeiyong=(hanshui*$bilishui)*(1+{$shuilv}/100) where ti_id=$aid and feetype={$data["feiyong_id"][$i]}");
                            }
                            //pizhunweishui 改为 hanshui

                        }
                    }
                }
                $dataup = ["id" => $aid, "fb" => 1, "fd_id" => $res2];
                Db::table("cg_ti")->update($dataup);
            } catch (\Exception $e) {
                echo $e->getMessage();
                Db::rollBack();die;
                return json_encode(["msg" => $e->getMessage(), "state" => 2]);
            }
            if ($res2) {
                if($data["state"]==3){
                    //$jieguo=$this->gowork(24,$res2);  //原来是17，改为 24
                    $jieguo=$this->gowork(17,$res2);  //原来是17，改为 24
                    if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                        Db::commit();
                        return $jieguo;
                    }else{
                        Db::rollBack();
                        return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                    }
                }else{
                    Db::commit();
                    return json_encode(["msg" => "", "state" => 1]);
                }



            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }
        } else {
            return json_encode(["msg" => "请正确提交", "state" => 2]);
        }
    }  // totalExpectedSales : yesSales 总预计销量; totalBenchmarkSales : noSales 总基准销量  ywlx

    //核销
    public function hexiao($aid, $type = 0)
    {
        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->where(["ap.id" => $aid])->field("jx.title as jxs,jx.sn,ec.em_name as cname")->find();

        $this->assign("apply", $apply);
        $where = "ap.id=$aid  ";
        switch ($type) {
            case 0:
                #可核销
                $where .= "and apd.hx_status=0 and (apd.hx_wsq is null or apd.hx_wsq>0)";
                break;
            case 2:
                #不予核销
                $where .= "and apd.hx_status=2";
                break;
            case 1:
                #核销中
                $where .= "and apd.hx_status=1";
                break;
            case 3:
                #未反馈
                $where .= "and apd.hx_status=3";
                break;
            case 4:
                #未反馈
                $where .= "and apd.hx_status=4";
                break;
            case 5:
                #未反馈
                $where .= "and apd.is_lock=1";
                break;
            case 6:
                $where .= "and apd.hx_status=5";
                break;
            default:
                # code...
                break;
        }

        $ade = Db::table("cg_ti_list")->alias("apd")
            ->join("cg_ti ap", "apd.ti_id=ap.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            /*->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")// 系统*/
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")      // 网点
            ->join("cg_system s", "apd.xt_id=s.id", "LEFT")  // 系统
            ->join("cg_jxs j", "apd.jxs_id=j.id", "LEFT")  // 经销商
            ->join("pro_products p", "apd.product=p.id","LEFT")
            ->join("pro_sku sk", "apd.sku=sk.id","LEFT")
            ->join("pro_series ps", "apd.series=ps.id","LEFT")
            ->join("pro_category pc", "apd.category=pc.id","LEFT")
            ->join("pro_brands pb", "apd.brand=pb.id","LEFT")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id","LEFT")
            ->where($where)->order("apd.id")
            ->field("apd.id,ap.sn as no,apd.sn as detail_no,ec.em_name as cname,n.title as net_name,
            s.title as sys_name,j.title as jxs,pb.brand_name,pc.category_name,ps.series_name,sk.sku_name,p.pro_name,f3.title as kemu3,apd.fb_shijiweishui as fankuijine,apd.fb_hanshui as fankuihanshui,apd.hx_yihexiao,apd.hx_sqz,apd.paymethod as zfid,apd.start as start_time,apd.fb_shuilv as fankuishuilv,ap.id as apid,apd.fb_shijitourufeiyong,apd.fb_isVAT")
            //->field("apd.id,ap.sn as no,apd.sn as detail_no,ec.em_name as cname,n.title as net_name,s.title as sys_name,pb.brand_name,f3.title as kemu3,apd.fb_shijiweishui as fankuijine,apd.fb_hanshui as fankuihanshui,apd.hx_yihexiao,apd.hx_sqz,apd.paymethod as zfid,apd.start as start_time,apd.fb_shuilv as fankuishuilv,ap.id as apid,apd.fb_shijitourufeiyong,apd.fb_isVAT")
            ->select(); //brand_name,category_name,series_name,sku_name,pro_name

        foreach ($ade as $k=>&$v){
            if($k==0){
                $v['brandnum']=0;
                $v['categorynum']=0;
                $v['seriesnum']=0;
                $v['skunum']=0;
                $v['pronum']=0;
            }

        }

        for ($i = 0; $i < count($ade); $i++) {
            $ade[$i]["hexiao"] = $ade[$i]["hx_yihexiao"] + $ade[$i]["hx_sqz"];
            $ade[$i]["weihe"] = $ade[$i]["fankuijine"] - $ade[$i]["hexiao"];
            $ade[$i]["weiheh"]=$ade[$i]["weihe"]*(1+$ade[$i]["fankuishuilv"]/100);
            if($ade[$i]["fb_isVAT"])
                $ade[$i]["weihes"]=$ade[$i]["weihe"];
            else
                $ade[$i]["weihes"]=$ade[$i]["weiheh"];
            $ade[$i]["start_time"] = date("Y-m-d", $ade[$i]["start_time"]);

            $ade[$i]["sj"]=$ade[$i]["weiheh"]-$ade[$i]["weihe"];
        }
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);
        $this->assign("ade", $ade);
        $this->assign("aid", $aid);
        $this->assign("type", $type);
        return $this->fetch();
    }

    //设置发票信息
    public function setfapiao()
    {
        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);

        return $this->fetch();
    }



    //网点反馈处理
    public function wangdianfan()
    {
        $request = Request::instance();


        $data = $request->post();
       // p($data);
        if ($data) {
            $aid = $data["aid"];

            //print_r($data);exit;
            $strnum = $this->producefbSN();
            $datalist = ["no" => $strnum, "type" => 0, "apply_id" => $aid, "c_user_id" => Session::get("employee_id"), "created_on" => date("Y-m-d H:i:s"), "state" => 1,
                "remark" => $data["remark"], "fujian" => $data["attach"]
            ];
            //$pro=Db::table("cg_ti_list")-> ti_id=$aid
            //echo 'cp_type';
            $pro=Db::table("cg_ti_list")->where(["ti_id"=>$aid])->value("cp_type");
            //p($pro);

            /*//try
            Db::startTrans();
                try {*/
            $feedbacktype = $data["feedbacktype"];

            //p($pro);
            if($feedbacktype==1){
                switch ($pro) {
                    case 0:
                        $product='brand'; //brand_name  代替 pro_name
                        //echo 'tyu';die; pro_no
                        $apde = Db::table("cg_ti_list")->query("
                   select apd.net_id,apd.brand as pro_id,p.brand_name,
                   sum(apd.boxnum) as sellnums,sum(apd.pizhunweishui) as yuji,sum(apd.totalExpectedSales) as xiaoshoue  
                   from cg_ti_list as apd 
                   inner join pro_brands as p on apd.brand=p.id 
                   inner join cg_net as n on apd.net_id=n.id 
                   where apd.ti_id=$aid 
                   group by apd.net_id,apd.brand");
                        break;
                    case 1:
                        $product='category';  //category_name  代替 pro_name
                        $apde = Db::table("cg_ti_list")->query("
                   select apd.net_id,apd.category as pro_id,p.category_name,
                   sum(apd.boxnum) as sellnums,sum(apd.pizhunweishui) as yuji,sum(apd.totalExpectedSales) as xiaoshoue  
                   from cg_ti_list as apd 
                   inner join pro_category as p on apd.category=p.id  
                   inner join cg_net as n on apd.net_id=n.id 
                   where apd.ti_id=$aid 
                   group by apd.net_id,apd.category");//n
                        break;
                    case 2:
                        $product='series';
                        $apde = Db::table("cg_ti_list")->query("
                   select apd.net_id,apd.series as pro_id,p.series_name,n.title as net_name,n.sn as net_no,
                   sum(apd.boxnum) as sellnums,sum(apd.pizhunweishui) as yuji,sum(apd.totalExpectedSales) as xiaoshoue   
                   from cg_ti_list as apd 
                   inner join pro_series as p on apd.series=p.id  // 代替 pro_products
                   inner join cg_net as n on apd.net_id=n.id 
                   where apd.ti_id=$aid 
                   group by apd.net_id,apd.series");
                        break;
                    case 3:
                        $product='sku';
                        $apde = Db::table("cg_ti_list")->query("
                   select apd.net_id,apd.sku as pro_id,p.sku_name,n.title as net_name,n.sn as net_no,
                   sum(apd.boxnum) as sellnums,sum(apd.pizhunweishui) as yuji,sum(apd.totalExpectedSales) as xiaoshoue  
                   from cg_ti_list as apd 
                   inner join pro_sku as p on apd.sku=p.id // 代替 pro_products
                   inner join cg_net as n on apd.net_id=n.id 
                   where apd.ti_id=$aid 
                   group by apd.net_id,apd.sku");
                        break;
                    case 4:
                        $product='product';
                        $apde = Db::table("cg_ti_list")->query("
                   select apd.net_id,apd.product as pro_id,p.pro_name,n.title as net_name,n.sn as net_no,
                   p.pro_no,sum(apd.boxnum) as sellnums,sum(apd.pizhunweishui) as yuji,sum(apd.totalExpectedSales) as xiaoshoue 
                   from cg_ti_list as apd 
                   inner join pro_products as p on apd.product=p.id 
                   inner join cg_net as n on apd.net_id=n.id 
                   where apd.ti_id=$aid 
                   group by apd.net_id,apd.product");
                        break;

                }

            }elseif ($feedbacktype==2){//系统  net_id 改为 xt_id 并命名未 net_id   cg_net 改为 cg_system    select apd.net_id, 改为 select apd.xt_id as net_id,
                switch ($pro) {
                    case 0:
                        $product='brand'; //brand_name  代替 pro_name
                        //echo 'tyu';die; pro_no
                        $apde = Db::table("cg_ti_list")->query("
                   select apd.xt_id as net_id,apd.brand as pro_id,p.brand_name,
                   sum(apd.boxnum) as sellnums,sum(apd.pizhunweishui) as yuji,sum(apd.totalExpectedSales) as xiaoshoue  
                   from cg_ti_list as apd 
                   inner join pro_brands as p on apd.brand=p.id 
                   inner join cg_system as n on apd.xt_id=n.id 
                   where apd.ti_id=$aid 
                   group by apd.xt_id,apd.brand");
                        break;
                    case 1:
                        $product='category';  //category_name  代替 pro_name
                        $apde = Db::table("cg_ti_list")->query("
                   select apd.xt_id as net_id,apd.category as pro_id,p.category_name,
                   sum(apd.boxnum) as sellnums,sum(apd.pizhunweishui) as yuji,sum(apd.totalExpectedSales) as xiaoshoue  
                   from cg_ti_list as apd 
                   inner join pro_category as p on apd.category=p.id  
                   inner join cg_system as n on apd.xt_id=n.id 
                   where apd.ti_id=$aid 
                   group by apd.xt_id,apd.category");//n
                        //p($apde);
                        //echo Db::table("cg_ti_list")->getLastSql();die;
                        break;
                    case 2:
                        $product='series';
                        $apde = Db::table("cg_ti_list")->query("
                   select apd.xt_id as net_id,apd.series as pro_id,p.series_name,n.title as net_name,n.sn as net_no,
                   sum(apd.boxnum) as sellnums,sum(apd.pizhunweishui) as yuji,sum(apd.totalExpectedSales) as xiaoshoue   
                   from cg_ti_list as apd 
                   inner join pro_series as p on apd.series=p.id  // 代替 pro_products
                   inner join cg_system as n on apd.xt_id=n.id 
                   where apd.ti_id=$aid 
                   group by apd.xt_id,apd.series");
                        break;
                    case 3:
                        $product='sku';
                        $apde = Db::table("cg_ti_list")->query("
                   select apd.xt_id as net_id,apd.sku as pro_id,p.sku_name,n.title as net_name,n.sn as net_no,
                   sum(apd.boxnum) as sellnums,sum(apd.pizhunweishui) as yuji,sum(apd.totalExpectedSales) as xiaoshoue  
                   from cg_ti_list as apd 
                   inner join pro_sku as p on apd.sku=p.id // 代替 pro_products
                   inner join cg_system as n on apd.xt_id=n.id 
                   where apd.ti_id=$aid 
                   group by apd.xt_id,apd.sku");
                        break;
                    case 4:
                        $product='product';
                        $apde = Db::table("cg_ti_list")->query("
                   select apd.xt_id as net_id,apd.product as pro_id,p.pro_name,n.title as net_name,n.sn as net_no,
                   p.pro_no,sum(apd.boxnum) as sellnums,sum(apd.pizhunweishui) as yuji,sum(apd.totalExpectedSales) as xiaoshoue 
                   from cg_ti_list as apd 
                   inner join pro_products as p on apd.product=p.id 
                   inner join cg_system as n on apd.xt_id=n.id 
                   where apd.ti_id=$aid 
                   group by apd.xt_id,apd.product");
                        break;

                }
            }//  net_id 改为 xt_id     cg_net 改为 cg_system
        /*}catch (\Exception $e) {
        echo $product.'   <> ';//category
        echo $e->getMessage();die;
        Db::rollBack();
        return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
    }*/
    /*echo 'gg';  // 系统繁忙请稍后再试
    p($apde);*/

            /*}catch (\Exception $e) {
                    echo $product.'   <> ';//category
                echo $e->getMessage();die;
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }*/

           // $apde = Db::table("cg_ti_list")->query("select apd.net_id,apd.product as pro_id,p.pro_name,n.title as net_name,n.sn as net_no,p.pro_no,sum(apd.boxnum) as sellnums,sum(apd.pizhunweishui) as yuji,sum(apd.totalExpectedSales) as xiaoshoue from cg_ti_list as apd inner join pro_products as p on apd.product=p.id inner join cg_net as n on apd.net_id=n.id where apd.ti_id=$aid group by apd.net_id,apd.product");
            //echo 'ee';die;

            $fbi = Db::table("all_ti_feeback_list")->where(["apply_id" => $aid, "is_deleted" => 0, "state" => 7])->count();
            if ($fbi)
                return json_encode(["msg" => "本申请存在已通过的反馈申请，不能使用网点反馈", "state" => 2]);
            Db::startTrans();
            try {
                Db::table("all_ti_feeback_list")->where(["apply_id" => $aid])->update(["is_deleted" => 1]);
                $res2 = Db::table("all_ti_feeback_list")->insertGetId($datalist);
//p(count($data["nid"])); //8
                for ($i = 0; $i < count($data["nid"]); $i++) {
                    //echo $i;
                    /*echo 'eee';
                    p($apde);//*/
                    for ($j = 0; $j < count($apde); $j++) {
                        /*if($i==3){
                            echo '3'; die;
                        }*/
                        //echo '777';die;  //

                        if($feedbacktype==1){  //网点反馈
                            if ($data["nid"][$i] == $apde[$j]["net_id"] && $data["pid"][$i] == $apde[$j]["pro_id"]) {  //没有进来
                                if (trim($data["shuilv"][$i]))
                                    $shuilv = $data["shuilv"][$i];
                                else
                                    $shuilv = 0;

                                //核算数量比例  不需要
                                // $box_bi = $data["box_num"][$i] / $apde[$j]["sellnums"];
                                //核算金额比例
                                /*echo 'wwww';die;
                                $jinebili = $data["hexiaojine"][$i] / $apde[$j]["yuji"];
                                echo '';die;
                                echo $jinebili.'rrr';die;*/
                                $nowt = time();
                                $user = Session::get("employee_id");

                                // p($data);   4444

                                if($data["is_di"][$i]){
                                    $res = Db::name('cg_ti_list')->where(['ti_id'=>$aid,'net_id'=>$data["nid"][$i],$product=>$data["pid"][$i]])->update([
                                        'fb_shuilv'=>$shuilv,
                                        'fb_isVAT'=>$data["is_di"][$i],
                                        'fb_shijixiaoliang'=>$data["box_num"][$i],
                                        'fb_brief'=>$data["remark"],
                                        'fb_shijiweishui'=>$data["hexiaojine"][$i],
                                        'fb_hanshui'=>$data["hexiaojine"][$i]+($data["hexiaojine"][$i])*$shuilv/100,
                                        'fb_shijitourufeiyong'=>$data["hexiaojine"][$i],
                                        'fb_time'=>$nowt,
                                        'fb_user'=>$user,
                                        'hx_status'=>5,
                                    ]);
                                    /*$res = Db::table("cg_ti_list")->query("
                                               update cg_ti_list
                                               set fb_shuilv={$shuilv},fb_isVAT={$data["is_di"][$i]},fb_shijixiaoliang={$data["box_num"][$i]},fb_brief='{$data["remark"]}',fb_shijiweishui='{$data["hexiaojine"][$i]}',
                                               fb_hanshui=('{$data["hexiaojine"][$i]}'+('{$data["hexiaojine"][$i]}')*{$shuilv}/100),fb_shijitourufeiyong='{$data["hexiaojine"][$i]}',fb_time=$nowt,fb_user=$user,hx_status=5
                                               where ti_id=$aid and net_id={$data["nid"][$i]} and {$product}={$data["pid"][$i]}");*/
                                }else{
                                    $res = Db::name('cg_ti_list')->where(['ti_id'=>$aid,'net_id'=>$data["nid"][$i],$product=>$data["pid"][$i]])->update([
                                        'fb_shuilv'=>$shuilv,
                                        'fb_isVAT'=>$data["is_di"][$i],
                                        'fb_shijixiaoliang'=>$data["box_num"][$i],
                                        'fb_brief'=>$data["remark"],
                                        'fb_shijiweishui'=>$data["hexiaojine"][$i],
                                        'fb_hanshui'=>$data["hexiaojine"][$i]+($data["hexiaojine"][$i])*$shuilv/100,
                                        'fb_shijitourufeiyong'=>$data["hexiaojine"][$i],
                                        'fb_time'=>$nowt,
                                        'fb_user'=>$user,
                                        'hx_status'=>5,
                                    ]);
                                }
                                /*echo Db::name("cg_ti_list")->getLastSql();
                                echo '</br>';*/
                            }
                        }elseif ($feedbacktype==2){  //系统反馈

                            //echo '2dd';die;
                           // p($data);//存在
                            //p($apde);// $apde[$j]["net_id"] 不存在
                            //echo $data["nid"][$i].':'.$apde[$j]["net_id"].';;'.$data["pid"][$i].':'.$apde[$j]["pro_id"];die;
                            if ($data["nid"][$i] == $apde[$j]["net_id"] && $data["pid"][$i] == $apde[$j]["pro_id"]) {  //没有进来
                                if (trim($data["shuilv"][$i]))
                                    $shuilv = $data["shuilv"][$i];
                                else
                                    $shuilv = 0;

                                //核算数量比例  不需要
                                // $box_bi = $data["box_num"][$i] / $apde[$j]["sellnums"];
                                //核算金额比例
                                /*echo 'wwww';die;
                                $jinebili = $data["hexiaojine"][$i] / $apde[$j]["yuji"];
                                echo '';die;
                                echo $jinebili.'rrr';die;*/
                                $nowt = time();
                                $user = Session::get("employee_id");

                                // p($data);   4444

                                if($data["is_di"][$i]){
                                     //net_id 改为 xt_id
                                    $res = Db::name('cg_ti_list')->where(['ti_id'=>$aid,'xt_id'=>$data["nid"][$i],$product=>$data["pid"][$i]])->update([
                                        'fb_shuilv'=>$shuilv,
                                        'fb_isVAT'=>$data["is_di"][$i],
                                        'fb_shijixiaoliang'=>$data["box_num"][$i],
                                        'fb_brief'=>$data["remark"],
                                        'fb_shijiweishui'=>$data["hexiaojine"][$i],
                                        'fb_hanshui'=>$data["hexiaojine"][$i]+($data["hexiaojine"][$i])*$shuilv/100,
                                        'fb_shijitourufeiyong'=>$data["hexiaojine"][$i],
                                        'fb_time'=>$nowt,
                                        'fb_user'=>$user,
                                        'hx_status'=>5,
                                    ]);
                                    /*$res = Db::table("cg_ti_list")->query("
                                               update cg_ti_list
                                               set fb_shuilv={$shuilv},fb_isVAT={$data["is_di"][$i]},fb_shijixiaoliang={$data["box_num"][$i]},fb_brief='{$data["remark"]}',fb_shijiweishui='{$data["hexiaojine"][$i]}',
                                               fb_hanshui=('{$data["hexiaojine"][$i]}'+('{$data["hexiaojine"][$i]}')*{$shuilv}/100),fb_shijitourufeiyong='{$data["hexiaojine"][$i]}',fb_time=$nowt,fb_user=$user,hx_status=5
                                               where ti_id=$aid and net_id={$data["nid"][$i]} and {$product}={$data["pid"][$i]}");*/
                                }else{
                                    $res = Db::name('cg_ti_list')->where(['ti_id'=>$aid,'xt_id'=>$data["nid"][$i],$product=>$data["pid"][$i]])->update([
                                        'fb_shuilv'=>$shuilv,
                                        'fb_isVAT'=>$data["is_di"][$i],
                                        'fb_shijixiaoliang'=>$data["box_num"][$i],
                                        'fb_brief'=>$data["remark"],
                                        'fb_shijiweishui'=>$data["hexiaojine"][$i],
                                        'fb_hanshui'=>$data["hexiaojine"][$i]+($data["hexiaojine"][$i])*$shuilv/100,
                                        'fb_shijitourufeiyong'=>$data["hexiaojine"][$i],
                                        'fb_time'=>$nowt,
                                        'fb_user'=>$user,
                                        'hx_status'=>5,//反馈后值为0，不能为5
                                    ]);
                                }

                            }
                        }


                        //  p($apde);//好的
                        //  echo $data["nid"][$i].':'.$apde[$j]["net_id"].';;'.$data["pid"][$i].':'.$apde[$j]["pro_id"];die;
                        /*if ($data["nid"][$i] == $apde[$j]["net_id"] && $data["pid"][$i] == $apde[$j]["pro_id"]) {  //没有进来
                            if (trim($data["shuilv"][$i]))
                                $shuilv = $data["shuilv"][$i];
                            else
                                $shuilv = 0;
                            $nowt = time();
                            $user = Session::get("employee_id");
                            if($data["is_di"][$i]){
                                $res = Db::name('cg_ti_list')->where(['ti_id'=>$aid,'net_id'=>$data["nid"][$i],$product=>$data["pid"][$i]])->update([
                                    'fb_shuilv'=>$shuilv,
                                    'fb_isVAT'=>$data["is_di"][$i],
                                    'fb_shijixiaoliang'=>$data["box_num"][$i],
                                    'fb_brief'=>$data["remark"],
                                    'fb_shijiweishui'=>$data["hexiaojine"][$i],
                                    'fb_hanshui'=>$data["hexiaojine"][$i]+($data["hexiaojine"][$i])*$shuilv/100,
                                    'fb_shijitourufeiyong'=>$data["hexiaojine"][$i],
                                    'fb_time'=>$nowt,
                                    'fb_user'=>$user,
                                    'hx_status'=>5,
                                ]);
//                                $res = Db::table("cg_ti_list")->query("
//                                           update cg_ti_list
//                                           set fb_shuilv={$shuilv},fb_isVAT={$data["is_di"][$i]},fb_shijixiaoliang={$data["box_num"][$i]},fb_brief='{$data["remark"]}',fb_shijiweishui='{$data["hexiaojine"][$i]}',
//                                           fb_hanshui=('{$data["hexiaojine"][$i]}'+('{$data["hexiaojine"][$i]}')*{$shuilv}/100),fb_shijitourufeiyong='{$data["hexiaojine"][$i]}',fb_time=$nowt,fb_user=$user,hx_status=5
//                                           where ti_id=$aid and net_id={$data["nid"][$i]} and {$product}={$data["pid"][$i]}");
                            }else{
                                $res = Db::name('cg_ti_list')->where(['ti_id'=>$aid,'net_id'=>$data["nid"][$i],$product=>$data["pid"][$i]])->update([
                                    'fb_shuilv'=>$shuilv,
                                    'fb_isVAT'=>$data["is_di"][$i],
                                    'fb_shijixiaoliang'=>$data["box_num"][$i],
                                    'fb_brief'=>$data["remark"],
                                    'fb_shijiweishui'=>$data["hexiaojine"][$i],
                                    'fb_hanshui'=>$data["hexiaojine"][$i]+($data["hexiaojine"][$i])*$shuilv/100,
                                    'fb_shijitourufeiyong'=>$data["hexiaojine"][$i],
                                    'fb_time'=>$nowt,
                                    'fb_user'=>$user,
                                    'hx_status'=>5,
                                ]);
                            }
                            echo Db::name("cg_ti_list")->getLastSql();
                            echo '</br>';
                        }*/
                    }
                }
                //echo 'wwww';die;
                $dataup = ["id" => $aid, "fb" => 1, "fd_id" => $res2];
                Db::table("cg_ti")->update($dataup);
            } catch (\Exception $e) {
                //echo $e->getMessage();die; net_id
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }

            if ($res2) {

                if($data["state"]==3){
                    $jieguo=$this->gowork(17,$res2);
                    if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                        Db::commit();
                        return $jieguo;
                    }else{
                        Db::rollBack();
                        return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                    }
                }else{
                    Db::commit();//提交事务 执行SQL语句（开启事务的时候会关闭自动提交的）
                    return json_encode(["msg" => "", "state" => 1]);
                }


            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }

        } else {
            return json_encode(["msg" => "请正确提交", "state" => 2]);
        }
    }

    function checkDateFormat($date){ //匹配日期格式
        if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
        {
//检测是否为日期
            if(checkdate($parts[2],$parts[3],$parts[1]))
                return true;
            else return false;
        }
        else return false;
    }






    public function updateapply()
    {
        header("Content-type:text/html;charset=utf-8");
        $postData = $this->request->post();
        //p($postData);
        $aid = $postData['ti_id'];
        $ctime = $postData['ctime'];

        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->where("ap.id=$aid and apd.ctime=$ctime ")
            ->field(" apd.ctime,ap.id,apd.start,apd.end,apd.brief,apd.cp_type,noSales,yesSales,feiyonglv,roi,expCanTime,start,end,ysstart,ysend")
            ->group('apd.ctime')
            ->find();
        // echo $postData['s1'];
//        $a=$this->checkDateFormat($postData['s1']);
        // print_r($a);die;

        if (isset($postData['expCanTime']) && $postData['expCanTime'] == 'NaN-NaN-NaN') {
            return json_encode(["msg" => "核销时间有误", "state" => "2"]);
        }


        if (isset($postData['s1']) && ($postData['s1'] == 'startvalue' || $postData['s1'] == 'undefined-undefined-undefined')) {
            $postData['s1'] = date('Y-m-d', $apply['start']);
            $postData['s2'] = date('Y-m-d', $apply['end']);
        }

        if (isset($postData['start']) && ($postData['start'] == 'startvalue' || $postData['s1'] == 'undefined-undefined-undefined')) {
            $postData['start'] = date('Y-m-d', $apply['ysstart']);
            $postData['end'] = date('Y-m-d', $apply['ysend']);
        }


        Db::table("cg_ti_list")->where("ti_id in($aid)  and ctime=$ctime")->delete();


        $fyl = $postData['yjfyl'];
        $fee = array(); //费用详情 的信息
        $feetype = array();//
        $jxsxt = array();
        $pp = array();
        $pl = array();
        $xl = array();
        $sku = array();
        $dp = array();

        $hbxx = array();
        if (!isset($postData['fRmb'])) {
            return json_encode(["msg" => "至少有一条费用明细", "state" => "2"]);
        }

        foreach ($postData as $k=>&$v){
            /*$hbnum = substr_count($k, 'hbxx');
            if($hbnum){
                if (!$v){
                }else{
                    $hbfh=str_replace("hbxx","","$k");
                    $hbdata=explode(';',$v);
                    foreach ($hbdata as $hk=>$hv){
                        $hbv=explode(',',$hv);
                        foreach ($hbv as  $hk2=>$hv2){
                            $hbv=explode(':',$hv2);
                            $hbxdata[$hk][$hbv[0]]=$hbv[1];
                        }
                    }
//                    dump($hbxdata);
                    foreach ($hbxdata as $kk=>&$vv){
                        $vv['ti_id']=$postData['ti_id'];
                        if(isset($vv['wlName'])){
                            $wlName=$vv['wlName'];
                        }
                        $where = "m_type=2 and is_deleted=0 and is_actived=1 ";
                        $data = Db::table('pro_materials t')->field('t.material_name,t.id,unit,factory')->where($where)->select();
                        foreach ($data as $mk=>$mv){
                            if($mv['material_name']==$wlName){
                                $vv['unit']=$mv['unit'];
                                $vv['factory']=$mv['factory'];
                            }
                        }
                    }
                    //p($hbxdata);
                    foreach ($hbxdata as $hbkk=>$hbvv){
                        Db::table('cg_ti_hb')->insert($hbvv);
                    }

                }
                $nums=count($hbxx);
                array_push($hbxx,"$v");
            }*/
            $number = substr_count($k, 'feetype');
            if($number){
                if (!$v){
                    return json_encode(["msg" => "费用类型不能为空", "state" => "2"]);
                }
                $strings=str_replace("feetype","","$k");
                $nums=count($feetype);
                $feetypes[$strings]=$nums;  //处理其他参数时需要，比如处理收款方, $nums在处理收款方时当键值
                array_push($feetype,"$v");
            }
            //客户详情 系统
            $number2 = substr_count($k, 'JinXiaoShangNum');
            if(isset($postData['khxqtype'])&&$postData['khxqtype']==2&&$number2){
                if (!$v){
                    return json_encode(["msg" => "客户详情请正确填写", "state" => "2"]);
                }
                $strings2=str_replace("JinXiaoShangNum","","$k");
                $nums2=count($jxsxt);
                $jxstypes[$strings2]=$nums2;  //处理其他参数时需要，比如处理收款方, $nums在处理收款方时当键值
                array_push($jxsxt,"$v");//系统投放网点数
            }

            //处理产品详情 品牌 品类 系列 SKU 单品
//品牌
            $number3 = substr_count($k, 'proTableInput0');
            if($number3){
                $strings3=str_replace("proTableInput0","","$k");
                $nums3=count($pp);
                $pptypes[$strings3]=$nums3;  //处理其他参数时需要
                array_push($pp,"$v");
            }
//品类
            $number4 = substr_count($k, 'proTableInput1');
            if($number4){
                $strings4=str_replace("proTableInput1","","$k");
                $nums4=count($pl);
                $pltypes[$strings4]=$nums4;  //处理其他参数时需要
                array_push($pl,"$v");
            }
//系列
            $number5 = substr_count($k, 'proTableInput2');
            if($number5){
                $strings5=str_replace("proTableInput2","","$k");
                $nums5=count($xl);
                $xltypes[$strings5]=$nums5;  //处理其他参数时需要
                array_push($xl,"$v");
            }
//SKU
            $number6 = substr_count($k, 'proTableInput3');
            if($number6){
                $strings6=str_replace("proTableInput3","","$k");
                $nums6=count($sku);
                $skutypes[$strings6]=$nums6;  //处理其他参数时需要
                array_push($sku,"$v");
            }
//单品
            $number7 = substr_count($k, 'proTableInput4');
            if($number7){
                $strings7=str_replace("proTableInput4","","$k");
                $nums7=count($dp);
                $dptypes[$strings7]=$nums7;  //处理其他参数时需要
                array_push($dp,"$v");
            }
        }
        //p($dp);

        $postData['feetype']=$feetype;//费用类型
        $postData['jxsxt']=$jxsxt;//客户详情  系统
        $ppnum=0;
        $plnum=0;
        $xlnum=0;
        $skunum=0;
        $dpnum=0;
        $i=1;
        $j=1;
        $j2=1;
        $j3=1;
        $j4=1;

        if (!empty($pp)){
            $ppnum = count($pp);
            $i=0;
            foreach ($pp as $k=>$v){
                if(!empty($v)){
                    $i++;
                }
            }
        }
        if (!empty($pl)){
            $plnum = count($pl);
            $j=0;
            foreach ($pl as $k=>$v){
                if(!empty($v)){
                    $j++;
                }
            }
        }
        if (!empty($xl)){
            $xlnum = count($xl);
            $j2=0;
            foreach ($xl as $k=>$v){
                if(!empty($v)){
                    $j2++;
                }
            }
        }//$pl
        if (!empty($sku)){
            $skunum = count($sku);
            $j3=0;
            foreach ($sku as $k=>$v){
                if(!empty($v)){
                    $j3++;
                }
            }
        }//$pl
        if (!empty($dp)){
            $dpnum = count($dp);
            $j4=0;
            foreach ($dp as $k=>$v){
                if(!empty($v)){
                    $j4++;
                }
            }
        }
        $postData['jxsxttype']='';
        if($ppnum==$i){
            $postData['jxsxttype']=0;
            $cpxqtype=0;
            //把 品牌 产品数据拿过来
        }elseif($plnum==$j){
            $postData['jxsxttype']=1;
            $cpxqtype=1;
            $pptypes=$pltypes;
            $pp=$pl;
        }elseif($xlnum==$j2){
            $postData['jxsxttype']=2;
            $cpxqtype=2;
            $pptypes=$xltypes;
            $pp=$xl;
        }elseif($skunum==$j3){
            $postData['jxsxttype']=3;
            $cpxqtype=3;
            $pptypes=$skutypes;
            $pp=$sku;
        }elseif($dpnum==$j4){
            $postData['jxsxttype']=4;
            $cpxqtype=4;
            $pptypes=$dptypes;
            $pp=$dp;
        }
        $postData['pp']=$pp;//客户详情  系统
        $postData['cpzb']=array();
        //产品详情  品牌，品类，系列，SKU,单品
        $cpxq['type']=$cpxqtype;
        //p($postData);
        foreach ($pptypes as $k=>$v){
            $ppnum='proTableInputBl'.$cpxqtype.$k;
            if(isset($pptypes[$k])){ //需要换 （改变）
                $num=$pptypes[$k];
                if(isset($pp[$num])){
                    if($cpxq['type']!=4){
                        $postData['ppnum'][$num]=$postData[$ppnum];
                        $cpxq['ppnum'][$num]=$postData[$ppnum];
                    }else{
                        $postData['ppnum'][$num]=null;
                        $cpxq['ppnum'][$num]=null;
                    }
                }else{
                }
            }else{
            }
            //p($cpxq);
            $ppsm='proTableInputSm'.$cpxqtype.$k;
            if(isset($pptypes[$k])){
                $num2=$pptypes[$k];
                if(isset($pp[$num])){
                    $postData['ppsm'][$num2]=$postData[$ppsm];
                    $cpxq['ppsm'][$num2]=$postData[$ppsm];  //客户详情 系统名称
                }else{
                }
            }else{
            }
            if(isset($postData['fylx'])&&$postData['fylx']==2) {
                $nowprice = 'nowprice' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['nowprice'][$num2] = $postData[$nowprice];
                        $cpxq['nowprice'][$num2] = $postData[$nowprice];  //客户详情 系统名称
                    } else {
                    }
                }

                $oldprices = 'oldprices' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['oldprices'][$num2] = $postData[$oldprices];
                        $cpxq['oldprices'][$num2] = $postData[$oldprices];  //客户详情 系统名称
                    }
                }

                $dealerZheJiaLv = 'dealerZheJiaLv' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['ZheJiaLv'][$num2] = $postData[$dealerZheJiaLv];
                        $cpxq['ZheJiaLv'][$num2] = $postData[$dealerZheJiaLv];  //客户详情 系统名称
                    }
                }


                $cpnum = 'num' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['cpnum'][$num2] = $postData[$cpnum];
                        $cpxq['cpnum'][$num2] = $postData[$cpnum];  //客户详情 系统名称
                    }
                }
            }elseif (isset($postData['fylx'])&&$postData['fylx']==4) {
                $nowprice = 'nowprice' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['nowprice'][$num2] = $postData[$nowprice];
                        $cpxq['nowprice'][$num2] = $postData[$nowprice];  //客户详情 系统名称
                    } else {
                    }
                }
                $nowprice2 = 'nowprice2' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['nowprice2'][$num2] = $postData[$nowprice2];
                        $cpxq['nowprice2'][$num2] = $postData[$nowprice2];  //客户详情 系统名称
                    } else {
                    }
                }

                $oldprices = 'oldprices' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['oldprices'][$num2] = $postData[$oldprices];
                        $cpxq['oldprices'][$num2] = $postData[$oldprices];  //客户详情 系统名称
                    }
                }

                $oldprices2 = 'oldprices2' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['oldprices2'][$num2] = $postData[$oldprices2];
                        $cpxq['oldprices2'][$num2] = $postData[$oldprices2];  //客户详情 系统名称
                    }
                }

                $dealerZheJiaLv = 'dealerZheJiaLv' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['ZheJiaLv'][$num2] = $postData[$dealerZheJiaLv];
                        $cpxq['ZheJiaLv'][$num2] = $postData[$dealerZheJiaLv];  //客户详情 系统名称
                    }
                }

                $dealerZheJiaLv2 = 'dealerZheJiaLv2' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['ZheJiaLv2'][$num2] = $postData[$dealerZheJiaLv2];
                        $cpxq['ZheJiaLv2'][$num2] = $postData[$dealerZheJiaLv2];  //客户详情 系统名称
                    }
                }

                $yls = 'yls' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['yls'][$num2] = $postData[$yls];
                        $cpxq['yls'][$num2] = $postData[$yls];  //客户详情 系统名称
                    }
                }

                $hdls = 'hdls' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['hdls'][$num2] = $postData[$hdls];
                        $cpxq['hdls'][$num2] = $postData[$hdls];  //客户详情 系统名称
                    }
                }

                $cpnum = 'num' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['cpnum'][$num2] = $postData[$cpnum];
                        $cpxq['cpnum'][$num2] = $postData[$cpnum];  //客户详情 系统名称
                    }
                }

            }elseif (isset($postData['fylx'])&&$postData['fylx']==7){
                $lssghj = 'lssghj' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['lssghj'][$num2] = $postData[$lssghj];
                        $cpxq['lssghj'][$num2] = $postData[$lssghj];  //客户详情 系统名称
                    } else {
                    }
                }

                $mclsj = 'mclsj' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['mclsj'][$num2] = $postData[$mclsj];
                        $cpxq['mclsj'][$num2] = $postData[$mclsj];  //客户详情 系统名称
                    } else {
                    }
                }

            }
        }

        $cpxq['name']=$pp;
        if(isset($cpxq['type'])&&$cpxq['type']==4){
            if(isset($cpxq['name'])&&isset($cpxq['ppnum'])){
                $cpnum=count($cpxq['ppnum']);
                foreach ($cpxq['ppnum'] as $ppk=>&$ppv){
                    $ppv=round(100/$cpnum,2);
                }
            }
        }

        switch ($cpxq['type']){
            case 0:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_brands')->where(['id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    //$cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;
                }
                $cpxq['brand']=$cpxq['name'];
                break;
            case 1:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_category')->alias("cat")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    //$cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;
                }
                $cpxq['category']=$cpxq['name'];
                break;
            case 2:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_series')->alias("ser")
                        ->join("pro_category cat","ser.category_id=cat.id")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    //$cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;

                }
                $cpxq['series']=$cpxq['name'];
                break;
            case 3:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_sku')->alias("sku")
                        ->join("pro_series ser","sku.series_id=ser.id")
                        ->join("pro_category cat","ser.category_id=cat.id")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    //$cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;
                }
                $cpxq['sku']=$cpxq['name'];
                break;
            case 4:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_products')->alias("pro")
                        ->join("pro_sku sku","pro.sku_id=sku.id")
                        ->join("pro_series ser","sku.series_id=ser.id")
                        ->join("pro_category cat","ser.category_id=cat.id")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    //$cpxq['product'][$cpk]=null;
                }
                $cpxq['product']=$cpxq['name'];
                break;

        }
        //产品详情
        //echo '1';
        /*Db::startTrans();
        try {*/
        $postData['jxsxtname']=array();
        $postData['jxsxtnum']=array();
        if(isset($postData['khxqtype'])&&$postData['khxqtype']==2){
            foreach ($jxstypes as $k=>$v){
                $xtnum='JinXiaoShang'.$k;
                $payee=$k;
                if(isset($jxstypes[$k])){
                    $num=$jxstypes[$k];
                    if(isset($jxsxt[$num])){
                        $postData['jxsxt'][$num]=$postData[$xtnum];
                        $jxsnum['jxsxt'][$num]=$postData[$xtnum]; //客户详情 系统 网点数
                        $khxq['jxsxt'][$num]=$postData[$xtnum];
                    }else{
                    }

                }else{
                }
                $xtname='JinXiaoShangBl'.$k;
                $payee=$k;
                if(isset($jxstypes[$payee])){
                    $num=$jxstypes[$payee];
                    if(isset($jxsxt[$num])){
                        $postData['jxsxtname'][$num]=$postData[$xtname];
                        $jxsname['jxsxtzb'][$num]=$postData[$xtname];  //客户详情 系统名称
                        $khxq['jxsxtzb'][$num]=$postData[$xtname];
                    }else{
                    }

                }else{
                }
            }
            $khxq['jxsxtwetnum']=$jxsxt;
            foreach ($jxstypes as $k=>$v){
                $xtnum='JinXiaoShangNum'.$k;
                $payee=$k;
                if(isset($jxstypes[$k])){
                    $num=$jxstypes[$k];
                    if(isset($feetype[$num])){
                        $postData['jxsxtnum'][$num]=$postData[$xtnum];
                        $jxsnum['jxsxtnum'][$num]=$postData[$xtnum]; //客户详情 系统 网点数
                    }else{
                    }

                }else{
                }
//改为占比
                $xtname='JinXiaoShangBl'.$k;
                $payee=$k;
                if(isset($jxstypes[$payee])){
                    $num=$jxstypes[$payee];
                    if(isset($feetype[$num])){
                        $postData['jxsxtzb'][$num]=$postData[$xtname];
                        $jxsname['jxsxtzb'][$num]=$postData[$xtname];  //客户详情 系统名称
                    }else{
                    }

                }else{
                }
            }
        }
        /*} catch (\Exception $e) {
            Db::rollBack();echo $e->getMessage();die;
            return json_encode(["wrong" => "系统繁忙请稍后再试", "aid" => ""]);
        }*/
        /*
         * 费用类型处理
        */
        //未税总额
        if(isset($postData['fRmb']) && is_array($postData['fRmb'])){
            foreach ($postData['fRmb'] as $k1=>$v1){
                if (empty($v1)){
                    return json_encode(["msg" => "未税总额不能为空", "state" => "2"]);
                }
            }
        }
        //支付方式
        if(isset($postData['status']) && is_array($postData['status'])){
            foreach ($postData['status'] as $k1=>$v1){
                if (empty($v1)){
                    return json_encode(["msg" => "支付方式不能为空", "state" => "2"]);
                }
            }
        }
        $fee['feetype']=$feetype; //费用类型
        $fee['fRmb']=$postData['fRmb']; //未税总额
        $fee['status']=$postData['status'];//支付方式
        $fee['fbreif']=$postData['fbreif']; //费用说明

        $postData['payee']=array();

        foreach ($feetypes as $k=>$v){
            //收款方
            $payees='payee'.$k;
            $payee=$k;
            if(isset($feetypes[$payee])){
                $num=$feetypes[$payee];
                if(isset($feetype[$num])){
                    $postData['payee'][$num]=$postData[$payees];
                    $fee['payee'][$num]=$postData[$payees];
                }else{
                }

            }else{
            }

            // 货补信息 payees
            $hbxxs='hbxx'.$k;
            $payee=$k;
            $hbxdata=array();
            if(isset($feetypes[$payee])){
                $num=$feetypes[$payee];
                if(isset($feetype[$num])) {
                    $postData['hbxx'][$num] = $postData[$hbxxs];
                    $fee['hbxx'][$num] = $postData[$hbxxs];
                    try {
                        $hbdata = explode(';', $postData[$hbxxs]);
                        foreach ($hbdata as $hk => $hv) {
                            if(!empty($hv)){
                                $hbv = explode(',', $hv);
                                foreach ($hbv as $hk2 => $hv2) {
                                    $hbv = explode(':', $hv2);
                                    if(isset($hbv[1])){
                                        $hbxdata[$hk][$hbv[0]] = $hbv[1];
                                    }
                                }
                            }
                        }
                        foreach ($hbxdata as $kk2 => &$vv2) {
                            if(isset($fee['feetype'][$v])){
                                $vv2['fylx']=$fee['feetype'][$v];
                            }else{
                                $vv2['fylx']='';
                            }
                            $vv2['fylx']=$fee['feetype'][$v];
                            $vv2['ti_id'] = $postData['ti_id'];
                            if (isset($vv2['wlName'])) {
                                $wlName = $vv2['wlName'];
                            }
                            $where = "m_type=2 and is_deleted=0 and is_actived=1 ";

                            if(isset($vv2['wlyptype'])&&$vv2['wlyptype']==1){ //物料
                                $data = Db::table('pro_materials t')->field('t.material_name,t.id,unit,factory')->where(['material_name'=>$vv2['wlName']])->find();
                                $vv2['unit'] = $data['unit'];
                                $vv2['factory'] = $data['factory'];
                            }else{ //样品
                                $data = Db::table('pro_products')->alias("p")
                                    ->join("pro_price pp", "pp.pid=p.id")
                                    ->field('p.pro_name,pp.factory,p.unit')->where(['p.pro_name'=>$vv2['wlName']])->find();
                                if(!empty($data)){
                                    $vv2['unit'] = $data['unit'];
                                    $vv2['factory'] = $data['factory'];
                                }
                            }
                        } // $kk  $vv


                    } catch (\Exception $e) {
                        return $e->getMessage();die;
                        Db::rollBack();
                        return json_encode(["msg" => "系统繁忙请稍后再试", "state" => "2"]);
                    }

                }else{
                }

            }

            $allhb[$v]=$hbxdata;
            foreach ($hbxdata as $hk=>$hv){
                $allhb2[]=$hv;
            }


            //陈列方式
            $cl_types='cl_type'.$k;
            $cl_type=$k;
            if(isset($feetypes[$cl_type])){

                $num=$feetypes[$cl_type];
                if(isset($feetype[$num])){
                    $postData['cl_type'][$num]=$postData[$cl_types];
                    if(!empty($postData[$cl_types])){
                        $fee['cl_type'][$num]=$postData[$cl_types];
                    }else{
                        $fee['cl_type'][$num]=Null;
                    }
                }
            }
            $cl_places='cl_place'.$k;
            $cl_place=$k;
            if(isset($feetypes[$cl_place])){
                $num=$feetypes[$cl_place];
                if(isset($feetype[$num])){
                    $postData['cl_place'][$num]=$postData[$cl_places];

                    if(!empty($postData[$cl_places])){
                        $fee['cl_place'][$num]=$postData[$cl_places];
                    }else{
                        $fee['cl_place'][$num]=Null;
                    }

                }

            }

            $cl_sizes='cl_size'.$k;
            $cl_size=$k;
            if(isset($feetypes[$cl_size])){
                $num=$feetypes[$cl_size];
                if(isset($feetype[$num])){
                    $postData['cl_size'][$num]=$postData[$cl_sizes];

                    if(!empty($postData[$cl_sizes])){
                        $fee['cl_size'][$num]=$postData[$cl_sizes];
                    }else{
                        $fee['cl_size'][$num]=Null;
                    }

                }
            }


//payee

            //成本中心
            $cbzx='cbzx'.$k;
            $payee=$k;
            if(isset($feetypes[$payee])){
                $num=$feetypes[$payee];
                if(isset($feetype[$num])){
                    //处理成本中心
                    if(isset($postData[$cbzx])&&!empty($postData[$cbzx])){

                    }else{
                        $postData[$cbzx]=$postData['zon'].',100%';
                    }

                    $fcbzx=explode(';',$postData[$cbzx]);
                    $fcb=array();
                    foreach ($fcbzx as $cbk=>$cbv){
                        $fcbzx2=explode(',',$cbv);
                        $fcb[$cbk]=$fcbzx2;
                    }
                    $fee['cbzx'][$num]=$fcb;
                }else{
                }
            }else{
            }

            //货补信息 hbxx

        }

        $abc=$allhb;
        $allhb22=$allhb;

        $fee['feetype']=$feetype;
        foreach ($postData['payee'] as $kk=>$vv){
            if (empty($vv)){
                return json_encode(["msg" => "供应商不能为空", "state" => "2"]);
            }elseif($vv<0){
                $postData['payeetype'][$kk]=1;//收款方是经销商
                $postData['payee'][$kk]=$postData['jxs_id'];
            }else{
                $postData['payeetype'][$kk]=2;//收款方是供应商
            }

        }
        $fee['payee']=$postData['payee'];//付款方id
        $fee['payeetype']=$postData['payeetype'];//付款方：1是经销商，2是供应商
        //p($postData);
        if($postData['khxqtype']==2){
            $netcount= count($khxq['jxsxt']);
        }elseif ($postData['khxqtype']==3){
            //数据处理
            if ($postData["nets"]) {
                $netsarr = explode(',', $postData["nets"]);
                $netcount=count($netsarr);
            } else {
                return json_encode(["msg" => "网点不能为空", "state" => "2"]);
            }
        }
        //客户 系统
        $feiyongcount = count($fee['feetype']);
        $procount = count($cpxq['ppnum']);
        //数据混编
        $datalist = [];
        $listnum = 0;
        $apply_id = $postData["ti_id"];
        $numnowdet = Db::table("cg_ti_list")->where(["ti_id" => $apply_id])->max("sn");

        $cbzxnum=0;
        for ($k = 0; $k < $feiyongcount; $k++) {
            $cbzxnum += count($fee['cbzx'][$k]);
        }
        if($postData['khxqtype']==2||$postData['khxqtype']==3){
            $tinum=$cbzxnum*$netcount*$procount;
        }elseif($postData['khxqtype']==1){
            $tinum=$cbzxnum*$procount;
        }

        if($postData['khxqtype']==2){ //客户详情是系统时
            for ($i = 0; $i < $netcount; $i++) {
                //$i循环网点
                //$j循环产品
                for ($j = 0; $j < $procount; $j++) {
                    //计算基准销量

                    //$j循环商品
                    for ($k = 0; $k < $feiyongcount; $k++) {
                        $cbcount = count($fee['cbzx'][$k]);
                        for ($l = 0;$l < $cbcount; $l++){   //成本中心
                            $alltouru='';
                            foreach ($fee['fRmb'] as $fk=>$fv){
                                $alltouru+=$fv;
                            }
                            $allcpzb=0;
                            foreach ($cpxq['profit'] as $zbk=>$zbv){
                                $allcpzb=floatval($allcpzb)+floatval($zbv);
                            }
                            $allroi=($postData['yesSales']-$postData['noSales'])/$alltouru*($allcpzb/$procount);
                            $aaa=($postData['yesSales']-$postData['noSales'])/$tinum*$cpxq['profit'][$j]*0.01;
                            $bbb=$fee['fRmb'][$k]*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000/(1+0.06);
                            $roi=$aaa/$bbb;
                            $roi=$roi*100;
                            $roi=round($roi, 2);

                            $hanshui=$fee['fRmb'][$k]*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000;//含税额
                            $yjsjtrfy=$hanshui/(1+0.06);//未税额，未抵扣即也是预计实际投入费用

                            /*$hanshui=$fee['fRmb'][$k]*(1+0.06);
                            $hanshui=$fee['fRmb'][$k]*(1+0.06);*/

                            /*if($yd[$j]["dikou"]){
                                $tmp["yjsjtrfy"]=$tmp["pizhunweishui"] ;
                            }else{
                                $tmp["yjsjtrfy"]= $tmp["pizhunhanshui"];
                            }*/

                            //当时特价补差类
                            if(isset($postData['fylx'])&&$postData['fylx']==4) {
                                $tmp = [
                                    "fylx"=>4,
                                    "fylxs"=>$postData["fylxs"],
                                    "khtype" => 2, //客户详情（经销商，系统，网点）
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "xt_id" => $khxq['jxsxt'][$i],  //系统
                                    "xt_zb" => $khxq['jxsxtzb'][$i],
                                    "net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   含税总额
                                    "amount" => $yjsjtrfy,//费用说明   未税额
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,//预计含税金额
                                    "pizhunhanshui" => $hanshui,//
                                    "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],

                                    "now_price"=>$cpxq['nowprice'][$j],//现价  ppsm
                                    "yuan_price"=>$cpxq['oldprices'][$j],//原价
                                    "zhejia"=>$cpxq['ZheJiaLv'][$j],//折价率
                                    "jizhunboxnum"=>$cpxq['cpnum'][$j],//箱数

                                    "wangdian_yuan" => $cpxq['oldprices2'][$j],  //网点原供货价
                                    "wangdian_price" => $cpxq['nowprice2'][$j],  //网点现供货价
                                    "wangdian_zhejia" => $cpxq['ZheJiaLv2'][$j],   //网点折价率
                                    "lingshou_price" => $cpxq['yls'][$j], //原零售价
                                    "huodong_price" => $cpxq['hdls'][$j],   //活动零售价
                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6  fylx
                                ];
                            }else if(isset($postData['fylx'])&&$postData['fylx']==7) {
                                $tmp = [
                                    "fylx"=>7,
                                    "fylxs"=>$postData["fylxs"],
                                    "khtype" => 2, //客户详情（经销商，系统，网点）
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "xt_id" => $khxq['jxsxt'][$i],  //系统
                                    "xt_zb" => $khxq['jxsxtzb'][$i],
                                    "net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   含税总额
                                    "amount" => $yjsjtrfy,//费用说明   未税额
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,//预计含税金额
                                    "pizhunhanshui" => $hanshui,//
                                    "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],

                                    "wangdian_price" => $cpxq['lssghj'][$j], //零售商供货价
                                    "lingshou_price" => $cpxq['mclsj'][$j],   //卖场零售价

                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }else{
                                $tmp = [
                                    "khtype" => 2, //客户详情（经销商，系统，网点）
                                    "fylxs"=>$postData["fylxs"],
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "xt_id" => $khxq['jxsxt'][$i],  //系统
                                    "xt_zb" => $khxq['jxsxtzb'][$i],
                                    "net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   含税总额
                                    "amount" => $yjsjtrfy,//费用说明   未税额
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,//预计含税金额
                                    "pizhunhanshui" => $hanshui,//
                                    "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],
                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }

//p($tmp);
                            $datalist[] = $tmp;
                            $listnum++;
                        }

                    }
                }

            }
        }elseif ($postData['khxqtype']==1){
            //$i循环网点
            //$j循环产品
            for ($j = 0; $j < $procount; $j++) {
                //计算基准销量
                //$j循环商品
                for ($k = 0; $k < $feiyongcount; $k++) {
                    $cbcount = count($fee['cbzx'][$k]);
                    for ($l = 0;$l < $cbcount; $l++){   //成本中心
                        $alltouru='';
                        foreach ($fee['fRmb'] as $fk=>$fv){
                            $alltouru+=$fv;
                        }

                        $allcpzb=0;
                        foreach ($cpxq['profit'] as $zbk=>$zbv){
                            $allcpzb=floatval($allcpzb)+floatval($zbv);
                        }

                        $allroi=($postData['yesSales']-$postData['noSales'])/$alltouru*($allcpzb/$procount);
                        $aaa=($postData['yesSales']-$postData['noSales'])/$tinum*$cpxq['profit'][$j]*0.01;
                        $bbb=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000/(1+0.06);//实际投入 ，未税投入
                        $roi=$aaa/$bbb;
                        $roi=$roi*100;
                        $roi=round($roi, 2);

                        $hanshui=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000;//含税额  没有系统占比
                        $yjsjtrfy=$hanshui/(1+0.06);//未税额，未抵扣即也是预计实际投入费用
                        if(isset($postData['fylx'])&&$postData['fylx']==2) {
                            $tmp = [
                                "fylx"=>2,
                                "fylxs"=>$postData["fylxs"],
                                "khtype" => 1, //客户详情是经销商
                                "cuser" => Session::get("employee_id"),
                                "puser" => Session::get("employee_id"),
                                "ctime" => time(), "ptime" => time(),
                                "sn" => $listnum + 1 + $numnowdet,
                                //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                //"xt_zb" => $khxq['jxsxtzb'][$i],
                                //"net_num" => $khxq['jxsxtwetnum'][$i],
                                "start" => strtotime($postData["s1"]),
                                "end" => strtotime($postData["s2"]),
                                "expCanTime" => strtotime($postData["expCanTime"]),
                                "ysstart" => strtotime($postData["start"]),//预算开始时间
                                "ysend" => strtotime($postData["end"]), //预算结束时间
                                "brief" => $postData["brief"],
                                "ti_id" => $postData["ti_id"],
                                "feetype" => $fee['feetype'][$k], //费用
                                "payee" => $fee['payee'][$k],//jxs_id
                                "payeetype" => $fee['payeetype'][$k],
                                "paymethod" => $fee['status'][$k],//支付方式
                                "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                "amount" => $yjsjtrfy,
                                "pizhunweishui" => $yjsjtrfy,
                                "cl_type" => $fee['cl_type'][$k],
                                "cl_place" => $fee['cl_place'][$k],
                                "cl_size" => $fee['cl_size'][$k],
                                "jxs_id" => $postData["jxs_id"],//产品
                                "brand" => $cpxq['brand'][$j],
                                "category" => $cpxq['category'][$j],
                                "series" => $cpxq['series'][$j],
                                "sku" => $cpxq['sku'][$j],
                                "product" => $cpxq['product'][$j],
                                "hanshui" => $hanshui,//预计含税金额
                                "pizhunhanshui" => $hanshui,
                                "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额
                                "cp_zb" => $cpxq['ppnum'][$j],
                                "cp_sm" => $cpxq['ppsm'][$j],
                                "cp_type" => $cpxq['type'],
                                "now_price"=>$cpxq['nowprice'][$j],//现价  ppsm
                                "yuan_price"=>$cpxq['oldprices'][$j],//原价
                                "zhejia"=>$cpxq['ZheJiaLv'][$j],//折价率
                                "jizhunboxnum"=>$cpxq['cpnum'][$j],//箱数
                                "cb_name" => $fee['cbzx'][$k][$l][0],
                                "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                "yujiroi"=>$roi,
                                "roi"=>$allroi,
                                //"yujifeiyonglv"=>$postData["yjfyl"],
                                "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"]
                                "yujifeiyonglv"=>$fyl,//费用率
                                "yjSalesType"=>$postData["yjSalesType"],
                                "noSales"=>$postData["noSales"],
                                "totalBenchmarkSales"=>$postData["noSales"],
                                "yesSales"=>$postData["yesSales"],
                                "totalExpectedSales"=>$postData["yesSales"],
                                "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                "hx_status" => 3,
                                "productlat" => $cpxq['type']+1,
                                "shuilv"=>6, // 税率默认为6
                            ];

                        }else{
                            $tmp = [
                                "khtype" => 1, //客户详情是经销商
                                "fylxs"=>$postData["fylxs"],
                                "cuser" => Session::get("employee_id"),
                                "puser" => Session::get("employee_id"),
                                "ctime" => time(), "ptime" => time(),
                                "sn" => $listnum + 1 + $numnowdet,
                                //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                //"xt_zb" => $khxq['jxsxtzb'][$i],
                                //"net_num" => $khxq['jxsxtwetnum'][$i],
                                "start" => strtotime($postData["s1"]),
                                "end" => strtotime($postData["s2"]),
                                "expCanTime" => strtotime($postData["expCanTime"]),
                                "ysstart" => strtotime($postData["start"]),//预算开始时间
                                "ysend" => strtotime($postData["end"]), //预算结束时间
                                "brief" => $postData["brief"],
                                "ti_id" => $postData["ti_id"],
                                "feetype" => $fee['feetype'][$k], //费用
                                "payee" => $fee['payee'][$k],//jxs_id
                                "payeetype" => $fee['payeetype'][$k],
                                "paymethod" => $fee['status'][$k],//支付方式
                                "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                "amount" => $yjsjtrfy,
                                "pizhunweishui" => $yjsjtrfy,
                                //$tmp["pizhunweishui"]

                                "cl_type" => $fee['cl_type'][$k],
                                "cl_place" => $fee['cl_place'][$k],
                                "cl_size" => $fee['cl_size'][$k],
                                "jxs_id" => $postData["jxs_id"],//产品
                                "brand" => $cpxq['brand'][$j],
                                "category" => $cpxq['category'][$j],
                                "series" => $cpxq['series'][$j],
                                "sku" => $cpxq['sku'][$j],
                                "product" => $cpxq['product'][$j],
                                "hanshui" => $hanshui,//预计含税金额
                                "pizhunhanshui" => $hanshui,
                                "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                                "cp_zb" => $cpxq['ppnum'][$j],
                                "cp_sm" => $cpxq['ppsm'][$j],
                                "cp_type" => $cpxq['type'],
                                "cb_name" => $fee['cbzx'][$k][$l][0],
                                "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                "yujiroi"=>$roi,
                                "roi"=>$allroi,
                                //"yujifeiyonglv"=>$postData["yjfyl"],
                                "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"]
                                "yujifeiyonglv"=>$fyl,//费用率
                                "yjSalesType"=>$postData["yjSalesType"],
                                "noSales"=>$postData["noSales"],
                                "totalBenchmarkSales"=>$postData["noSales"],
                                "yesSales"=>$postData["yesSales"],
                                "totalExpectedSales"=>$postData["yesSales"],
                                "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                "hx_status" => 3,
                                "productlat" => $cpxq['type']+1,
                                "shuilv"=>6, // 税率默认为6
                            ];
                        }


                        $datalist[] = $tmp;
                        $listnum++;
                    }

                }
            }

        }elseif ($postData['khxqtype']==3){
            for ($i = 0; $i < $netcount; $i++) {
                for ($j = 0; $j < $procount; $j++) {
                    //计算基准销量
                    //$j循环商品
                    for ($k = 0; $k < $feiyongcount; $k++) {
                        $cbcount = count($fee['cbzx'][$k]);
                        for ($l = 0;$l < $cbcount; $l++){   //成本中心
                            $alltouru='';
                            foreach ($fee['fRmb'] as $fk=>$fv){
                                $alltouru+=$fv;
                            }

                            //echo '8';
                            $allcpzb=0;
                            foreach ($cpxq['profit'] as $zbk=>$zbv){
                                $allcpzb=floatval($allcpzb)+floatval($zbv);
                            }

                            $allroi=($postData['yesSales']-$postData['noSales'])/$alltouru*($allcpzb/$procount);
                            $aaa=($postData['yesSales']-$postData['noSales'])/$tinum*$cpxq['profit'][$j]*0.01;
                            $bbb=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000/(1+0.06)/$netcount;

                            $roi=$aaa/$bbb;
                            $roi=$roi*100;
                            $roi=round($roi, 2);
                            //$hanshui=$fee['fRmb'][$k]*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000;//含税额
                            $hanshui=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000/$netcount;//含税额

                            $yjsjtrfy=$hanshui/(1+0.06);//未税额，未抵扣即也是预计实际投入费用
                            //echo 'tt';
                            /*echo $postData['fylx'];
                            p($cpxq);*/
                            if(isset($postData['fylx'])&&$postData['fylx']==4) {
                                $tmp = [
                                    "fylx"=>4,
                                    "khtype" => 3,
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "net_id" => $netsarr[$i],
                                    //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                    //"xt_zb" => $khxq['jxsxtzb'][$i],
                                    //"net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                    "amount" => $yjsjtrfy,
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,
                                    "pizhunhanshui" => $hanshui,
                                    "yjsjtrfy" => $yjsjtrfy,
                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],

                                    "now_price"=>$cpxq['nowprice'][$j],//现价  ppsm
                                    "yuan_price"=>$cpxq['oldprices'][$j],//原价
                                    "zhejia"=>$cpxq['ZheJiaLv'][$j],//折价率
                                    "jizhunboxnum"=>$cpxq['cpnum'][$j],//箱数
                                    "wangdian_yuan" => $cpxq['oldprices2'][$j],  //网点原供货价
                                    "wangdian_price" => $cpxq['nowprice2'][$j],  //网点现供货价
                                    "wangdian_zhejia" => $cpxq['ZheJiaLv2'][$j],   //网点折价率
                                    "lingshou_price" => $cpxq['yls'][$j], //原零售价
                                    "huodong_price" => $cpxq['hdls'][$j],   //活动零售价

                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"] 预计费用率
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }else if(isset($postData['fylx'])&&$postData['fylx']==7) {
                                $tmp = [
                                    "fylx"=>7,
                                    "khtype" => 3,
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "net_id" => $netsarr[$i],
                                    //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                    //"xt_zb" => $khxq['jxsxtzb'][$i],
                                    //"net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                    "amount" => $yjsjtrfy,
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,
                                    "pizhunhanshui" => $hanshui,
                                    "yjsjtrfy" => $yjsjtrfy,
                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],
                                    "wangdian_price" => $cpxq['lssghj'][$j], //零售商供货价
                                    "lingshou_price" => $cpxq['mclsj'][$j],   //卖场零售价

                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"] 预计费用率
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }else{
                                $tmp = [
                                    "khtype" => 3,
                                    "fylxs"=>$postData["fylxs"],
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "net_id" => $netsarr[$i],
                                    //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                    //"xt_zb" => $khxq['jxsxtzb'][$i],
                                    //"net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                    "amount" => $yjsjtrfy,
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,
                                    "pizhunhanshui" => $hanshui,
                                    "yjsjtrfy" => $yjsjtrfy,
                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],
                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"] 预计费用率
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }


                            $datalist[] = $tmp;
                            $listnum++;
                        }

                    }
                }

            }
        }

//type_id
        Db::startTrans();

        $tisq=Db::table("cg_ti")->where('id',$postData["ti_id"])->value('khtype');
        /*echo '555';
        die;*/

        try {
            $productlat=$cpxq['type']+1;
            $res1 = Db::table("cg_ti_list")->insertAll($datalist);
            //$sq=Db::table("cg_ti_list")->where('ti_id',$postData["ti_id"])->field('ctime')->find();
            $sq=Db::table('cg_ti_list')->where('ti_id',$postData["ti_id"])->order("ctime desc")->limit(1)->select();

            $hbsq = [];
            if($sq){
                foreach ($allhb as $k=>&$v){
                    foreach ($v as $kk=>&$vv){
                        $vv['ctime']=$sq['0']['ctime'];
                        $vv['money']=$vv['factory']*$vv['num'];
                        $hbsq[]=$vv;
                    }
                }
                $res2 = Db::table("cg_ti_hb")->insertAll($hbsq);
            }


        } catch (\Exception $e) {
            return $e->getMessage();die;
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => "2"]);
        }
        /*dump($res1);
        echo 'tisq';
        p($datalist);*/
        $productlat=$cpxq['type']+1;
        $tisq=Db::table("cg_ti")->where('id',$postData["ti_id"])->value('khtype');
        if(empty($tisq)){
            $data2=['id'=>$postData["ti_id"],'productlat'=>$productlat,'khtype'=>$postData['khxqtype']];
        }elseif ($tisq==$postData['khxqtype']){
            $data2=['id'=>$postData["ti_id"],'productlat'=>$productlat];
        }else{
            $data2=['id'=>$postData["ti_id"],'productlat'=>$productlat,'khtype'=>0];
        }

        //$data2=['id'=>$postData["ti_id"],'productlat'=>$productlat];
        $res3=Db::table("cg_ti")->update($data2);


        if ($res1) {

            Db::commit();
            return json_encode(["msg" => "操作已成功", "state" => "1"]);
        } else {
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => "2"]);
        }


    }

// 修改






//payee
    public function updateapply22()
    {
        header("Content-type:text/html;charset=utf-8");
        $postData = $this->request->post();
        //p($postData);
        $aid = $postData['ti_id'];
        $ctime = $postData['ctime'];

        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->where("ap.id=$aid and apd.ctime=$ctime ")
            ->field(" apd.ctime,ap.id,apd.start,apd.end,apd.brief,apd.cp_type,noSales,yesSales,feiyonglv,roi,expCanTime,start,end,ysstart,ysend")
            ->group('apd.ctime')
            ->find();
        // echo $postData['s1'];
//        $a=$this->checkDateFormat($postData['s1']);
        // print_r($a);die;

        if (isset($postData['expCanTime']) && $postData['expCanTime'] == 'NaN-NaN-NaN') {
            return json_encode(["msg" => "核销时间有误", "state" => "2"]);
        }


        if (isset($postData['s1']) && ($postData['s1'] == 'startvalue' || $postData['s1'] == 'undefined-undefined-undefined')) {
            $postData['s1'] = date('Y-m-d', $apply['start']);
            $postData['s2'] = date('Y-m-d', $apply['end']);
        }

        if (isset($postData['start']) && ($postData['start'] == 'startvalue' || $postData['s1'] == 'undefined-undefined-undefined')) {
            $postData['start'] = date('Y-m-d', $apply['ysstart']);
            $postData['end'] = date('Y-m-d', $apply['ysend']);
        }


        Db::table("cg_ti_list")->where("ti_id in($aid)  and ctime=$ctime")->delete();


        $fyl=$postData['yjfyl'];
        $fee=array(); //费用详情 的信息
        $feetype=array();//
        $jxsxt=array();
        $pp=array();
        $pl=array();
        $xl=array();
        $sku=array();
        $dp=array();

        $hbxx=array();
        if(!isset($postData['fRmb'])){
            return json_encode(["msg" => "至少有一条费用明细", "state" => "2"]);
        }

        foreach ($postData as $k=>&$v){
            /*$hbnum = substr_count($k, 'hbxx');
            if($hbnum){
                if (!$v){
                }else{
                    $hbfh=str_replace("hbxx","","$k");
                    $hbdata=explode(';',$v);
                    foreach ($hbdata as $hk=>$hv){
                        $hbv=explode(',',$hv);
                        foreach ($hbv as  $hk2=>$hv2){
                            $hbv=explode(':',$hv2);
                            $hbxdata[$hk][$hbv[0]]=$hbv[1];
                        }
                    }
                    foreach ($hbxdata as $kk=>&$vv){
                        $vv['ti_id']=$postData['ti_id'];
                        if(isset($vv['wlName'])){
                            $wlName=$vv['wlName'];
                        }
                        $where = "m_type=2 and is_deleted=0 and is_actived=1 ";
                        $data = Db::table('pro_materials t')->field('t.material_name,t.id,unit,factory')->where($where)->select();
                        foreach ($data as $mk=>$mv){
                            if($mv['material_name']==$wlName){
                                $vv['unit']=$mv['unit'];
                                $vv['factory']=$mv['factory'];
                            }
                        }
                    }
                    foreach ($hbxdata as $hbkk=>$hbvv){
                        Db::table('cg_ti_hb')->insert($hbvv);
                    }

                }
                $nums=count($hbxx);
                array_push($hbxx,"$v");
            }*/
            $number = substr_count($k, 'feetype');
            if($number){
                if (!$v){
                    return json_encode(["msg" => "费用类型不能为空", "state" => "2"]);
                }
                $strings=str_replace("feetype","","$k");
                $nums=count($feetype);
                $feetypes[$strings]=$nums;  //处理其他参数时需要，比如处理收款方, $nums在处理收款方时当键值
                array_push($feetype,"$v");
            }
            //客户详情 系统
            $number2 = substr_count($k, 'JinXiaoShangNum');
            if(isset($postData['khxqtype'])&&$postData['khxqtype']==2&&$number2){
                if (!$v){
                    return json_encode(["msg" => "客户详情请正确填写", "state" => "2"]);
                }
                $strings2=str_replace("JinXiaoShangNum","","$k");
                $nums2=count($jxsxt);
                $jxstypes[$strings2]=$nums2;  //处理其他参数时需要，比如处理收款方, $nums在处理收款方时当键值
                array_push($jxsxt,"$v");//系统投放网点数
            }

            //处理产品详情 品牌 品类 系列 SKU 单品
//品牌
            $number3 = substr_count($k, 'proTableInput0');
            if($number3){
                $strings3=str_replace("proTableInput0","","$k");
                $nums3=count($pp);
                $pptypes[$strings3]=$nums3;  //处理其他参数时需要
                array_push($pp,"$v");
            }
//品类
            $number4 = substr_count($k, 'proTableInput1');
            if($number4){
                $strings4=str_replace("proTableInput1","","$k");
                $nums4=count($pl);
                $pltypes[$strings4]=$nums4;  //处理其他参数时需要
                array_push($pl,"$v");
            }
//系列
            $number5 = substr_count($k, 'proTableInput2');
            if($number5){
                $strings5=str_replace("proTableInput2","","$k");
                $nums5=count($xl);
                $xltypes[$strings5]=$nums5;  //处理其他参数时需要
                array_push($xl,"$v");
            }
//SKU
            $number6 = substr_count($k, 'proTableInput3');
            if($number6){
                $strings6=str_replace("proTableInput3","","$k");
                $nums6=count($sku);
                $skutypes[$strings6]=$nums6;  //处理其他参数时需要
                array_push($sku,"$v");
            }
//单品
            $number7 = substr_count($k, 'proTableInput4');
            if($number7){
                $strings7=str_replace("proTableInput4","","$k");
                $nums7=count($dp);
                $dptypes[$strings7]=$nums7;  //处理其他参数时需要
                array_push($dp,"$v");
            }
        }
        //p($dp);

        $postData['feetype']=$feetype;//费用类型
        $postData['jxsxt']=$jxsxt;//客户详情  系统
        $ppnum=0;
        $plnum=0;
        $xlnum=0;
        $skunum=0;
        $dpnum=0;
        $i=1;
        $j=1;
        $j2=1;
        $j3=1;
        $j4=1;

        if (!empty($pp)){
            $ppnum = count($pp);
            $i=0;
            foreach ($pp as $k=>$v){
                if(!empty($v)){
                    $i++;
                }
            }
        }
        if (!empty($pl)){
            $plnum = count($pl);
            $j=0;
            foreach ($pl as $k=>$v){
                if(!empty($v)){
                    $j++;
                }
            }
        }
        if (!empty($xl)){
            $xlnum = count($xl);
            $j2=0;
            foreach ($xl as $k=>$v){
                if(!empty($v)){
                    $j2++;
                }
            }
        }//$pl
        if (!empty($sku)){
            $skunum = count($sku);
            $j3=0;
            foreach ($sku as $k=>$v){
                if(!empty($v)){
                    $j3++;
                }
            }
        }//$pl
        if (!empty($dp)){
            $dpnum = count($dp);
            $j4=0;
            foreach ($dp as $k=>$v){
                if(!empty($v)){
                    $j4++;
                }
            }
        }
        $postData['jxsxttype']='';
        if($ppnum==$i){
            $postData['jxsxttype']=0;
            $cpxqtype=0;
            //把 品牌 产品数据拿过来
        }elseif($plnum==$j){
            $postData['jxsxttype']=1;
            $cpxqtype=1;
            $pptypes=$pltypes;
            $pp=$pl;
        }elseif($xlnum==$j2){
            $postData['jxsxttype']=2;
            $cpxqtype=2;
            $pptypes=$xltypes;
            $pp=$xl;
        }elseif($skunum==$j3){
            $postData['jxsxttype']=3;
            $cpxqtype=3;
            $pptypes=$skutypes;
            $pp=$sku;
        }elseif($dpnum==$j4){
            $postData['jxsxttype']=4;
            $cpxqtype=4;
            $pptypes=$dptypes;
            $pp=$dp;
        }
        $postData['pp']=$pp;//客户详情  系统
        $postData['cpzb']=array();
        //产品详情  品牌，品类，系列，SKU,单品
        $cpxq['type']=$cpxqtype;
        //p($postData);
        foreach ($pptypes as $k=>$v){
            $ppnum='proTableInputBl'.$cpxqtype.$k;
            if(isset($pptypes[$k])){ //需要换 （改变）
                $num=$pptypes[$k];
                if(isset($pp[$num])){
                    if($cpxq['type']!=4){
                        $postData['ppnum'][$num]=$postData[$ppnum];
                        $cpxq['ppnum'][$num]=$postData[$ppnum];
                    }else{
                        $postData['ppnum'][$num]=null;
                        $cpxq['ppnum'][$num]=null;
                    }
                }else{
                }
            }else{
            }
            //p($cpxq);
            $ppsm='proTableInputSm'.$cpxqtype.$k;
            if(isset($pptypes[$k])){
                $num2=$pptypes[$k];
                if(isset($pp[$num])){
                    $postData['ppsm'][$num2]=$postData[$ppsm];
                    $cpxq['ppsm'][$num2]=$postData[$ppsm];  //客户详情 系统名称
                }else{
                }
            }else{
            }
            if(isset($postData['fylx'])&&$postData['fylx']==2) {
                $nowprice = 'nowprice' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['nowprice'][$num2] = $postData[$nowprice];
                        $cpxq['nowprice'][$num2] = $postData[$nowprice];  //客户详情 系统名称
                    } else {
                    }
                }

                $oldprices = 'oldprices' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['oldprices'][$num2] = $postData[$oldprices];
                        $cpxq['oldprices'][$num2] = $postData[$oldprices];  //客户详情 系统名称
                    }
                }

                $dealerZheJiaLv = 'dealerZheJiaLv' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['ZheJiaLv'][$num2] = $postData[$dealerZheJiaLv];
                        $cpxq['ZheJiaLv'][$num2] = $postData[$dealerZheJiaLv];  //客户详情 系统名称
                    }
                }


                $cpnum = 'num' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['cpnum'][$num2] = $postData[$cpnum];
                        $cpxq['cpnum'][$num2] = $postData[$cpnum];  //客户详情 系统名称
                    }
                }
            }elseif (isset($postData['fylx'])&&$postData['fylx']==4) {
                $nowprice = 'nowprice' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['nowprice'][$num2] = $postData[$nowprice];
                        $cpxq['nowprice'][$num2] = $postData[$nowprice];  //客户详情 系统名称
                    } else {
                    }
                }
                $nowprice2 = 'nowprice2' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['nowprice2'][$num2] = $postData[$nowprice2];
                        $cpxq['nowprice2'][$num2] = $postData[$nowprice2];  //客户详情 系统名称
                    } else {
                    }
                }

                $oldprices = 'oldprices' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['oldprices'][$num2] = $postData[$oldprices];
                        $cpxq['oldprices'][$num2] = $postData[$oldprices];  //客户详情 系统名称
                    }
                }

                $oldprices2 = 'oldprices2' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['oldprices2'][$num2] = $postData[$oldprices2];
                        $cpxq['oldprices2'][$num2] = $postData[$oldprices2];  //客户详情 系统名称
                    }
                }

                $dealerZheJiaLv = 'dealerZheJiaLv' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['ZheJiaLv'][$num2] = $postData[$dealerZheJiaLv];
                        $cpxq['ZheJiaLv'][$num2] = $postData[$dealerZheJiaLv];  //客户详情 系统名称
                    }
                }

                $dealerZheJiaLv2 = 'dealerZheJiaLv2' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['ZheJiaLv2'][$num2] = $postData[$dealerZheJiaLv2];
                        $cpxq['ZheJiaLv2'][$num2] = $postData[$dealerZheJiaLv2];  //客户详情 系统名称
                    }
                }

                $yls = 'yls' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['yls'][$num2] = $postData[$yls];
                        $cpxq['yls'][$num2] = $postData[$yls];  //客户详情 系统名称
                    }
                }

                $hdls = 'hdls' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['hdls'][$num2] = $postData[$hdls];
                        $cpxq['hdls'][$num2] = $postData[$hdls];  //客户详情 系统名称
                    }
                }

                $cpnum = 'num' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['cpnum'][$num2] = $postData[$cpnum];
                        $cpxq['cpnum'][$num2] = $postData[$cpnum];  //客户详情 系统名称
                    }
                }

            }elseif (isset($postData['fylx'])&&$postData['fylx']==7){
                $lssghj = 'lssghj' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['lssghj'][$num2] = $postData[$lssghj];
                        $cpxq['lssghj'][$num2] = $postData[$lssghj];  //客户详情 系统名称
                    } else {
                    }
                }

                $mclsj = 'mclsj' . $k;
                if (isset($pptypes[$k])) {
                    $num2 = $pptypes[$k];
                    if (isset($pp[$num])) {
                        $postData['mclsj'][$num2] = $postData[$mclsj];
                        $cpxq['mclsj'][$num2] = $postData[$mclsj];  //客户详情 系统名称
                    } else {
                    }
                }

            }
        }

        $cpxq['name']=$pp;
        if(isset($cpxq['type'])&&$cpxq['type']==4){
            if(isset($cpxq['name'])&&isset($cpxq['ppnum'])){
                $cpnum=count($cpxq['ppnum']);
                foreach ($cpxq['ppnum'] as $ppk=>&$ppv){
                    $ppv=round(100/$cpnum,2);
                }
            }
        }

        switch ($cpxq['type']){
            case 0:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_brands')->where(['id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    //$cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;
                }
                $cpxq['brand']=$cpxq['name'];
                break;
            case 1:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_category')->alias("cat")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    //$cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;
                }
                $cpxq['category']=$cpxq['name'];
                break;
            case 2:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_series')->alias("ser")
                        ->join("pro_category cat","ser.category_id=cat.id")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    //$cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;

                }
                $cpxq['series']=$cpxq['name'];
                break;
            case 3:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_sku')->alias("sku")
                        ->join("pro_series ser","sku.series_id=ser.id")
                        ->join("pro_category cat","ser.category_id=cat.id")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    //$cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;
                }
                $cpxq['sku']=$cpxq['name'];
                break;
            case 4:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_products')->alias("pro")
                        ->join("pro_sku sku","pro.sku_id=sku.id")
                        ->join("pro_series ser","sku.series_id=ser.id")
                        ->join("pro_category cat","ser.category_id=cat.id")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    //$cpxq['product'][$cpk]=null;
                }
                $cpxq['product']=$cpxq['name'];
                break;

        }
        //产品详情
        //echo '1';
        /*Db::startTrans();
        try {*/
        $postData['jxsxtname']=array();
        $postData['jxsxtnum']=array();
        if(isset($postData['khxqtype'])&&$postData['khxqtype']==2){
            foreach ($jxstypes as $k=>$v){
                $xtnum='JinXiaoShang'.$k;
                $payee=$k;
                if(isset($jxstypes[$k])){
                    $num=$jxstypes[$k];
                    if(isset($jxsxt[$num])){
                        $postData['jxsxt'][$num]=$postData[$xtnum];
                        $jxsnum['jxsxt'][$num]=$postData[$xtnum]; //客户详情 系统 网点数
                        $khxq['jxsxt'][$num]=$postData[$xtnum];
                    }else{
                    }

                }else{
                }
                $xtname='JinXiaoShangBl'.$k;
                $payee=$k;
                if(isset($jxstypes[$payee])){
                    $num=$jxstypes[$payee];
                    if(isset($jxsxt[$num])){
                        $postData['jxsxtname'][$num]=$postData[$xtname];
                        $jxsname['jxsxtzb'][$num]=$postData[$xtname];  //客户详情 系统名称
                        $khxq['jxsxtzb'][$num]=$postData[$xtname];
                    }else{
                    }

                }else{
                }
            }
            $khxq['jxsxtwetnum']=$jxsxt;
            foreach ($jxstypes as $k=>$v){
                $xtnum='JinXiaoShangNum'.$k;
                $payee=$k;
                if(isset($jxstypes[$k])){
                    $num=$jxstypes[$k];
                    if(isset($feetype[$num])){
                        $postData['jxsxtnum'][$num]=$postData[$xtnum];
                        $jxsnum['jxsxtnum'][$num]=$postData[$xtnum]; //客户详情 系统 网点数
                    }else{
                    }

                }else{
                }
//改为占比
                $xtname='JinXiaoShangBl'.$k;
                $payee=$k;
                if(isset($jxstypes[$payee])){
                    $num=$jxstypes[$payee];
                    if(isset($feetype[$num])){
                        $postData['jxsxtzb'][$num]=$postData[$xtname];
                        $jxsname['jxsxtzb'][$num]=$postData[$xtname];  //客户详情 系统名称
                    }else{
                    }

                }else{
                }
            }
        }
        /*} catch (\Exception $e) {
            Db::rollBack();echo $e->getMessage();die;
            return json_encode(["wrong" => "系统繁忙请稍后再试", "aid" => ""]);
        }*/
//echo '2';die;  //JinXiaoShang  JinXiaoShangs 1541672448000
        //dump($khxq); //客户详情网点信息
        /*
         * 费用类型处理
        */
        //未税总额
        if(isset($postData['fRmb']) && is_array($postData['fRmb'])){
            foreach ($postData['fRmb'] as $k1=>$v1){
                if (empty($v1)){
                    return json_encode(["msg" => "未税总额不能为空", "state" => "2"]);
                }
            }
        }
        //支付方式
        if(isset($postData['status']) && is_array($postData['status'])){
            foreach ($postData['status'] as $k1=>$v1){
                if (empty($v1)){
                    return json_encode(["msg" => "支付方式不能为空", "state" => "2"]);
                }
            }
        }
        $fee['feetype']=$feetype; //费用类型
        $fee['fRmb']=$postData['fRmb']; //未税总额
        $fee['status']=$postData['status'];//支付方式
        $fee['fbreif']=$postData['fbreif']; //费用说明

        $postData['payee']=array();

        foreach ($feetypes as $k=>$v){
            //收款方
            $payees='payee'.$k;
            $payee=$k;
            if(isset($feetypes[$payee])){
                $num=$feetypes[$payee];
                if(isset($feetype[$num])){
                    $postData['payee'][$num]=$postData[$payees];
                    $fee['payee'][$num]=$postData[$payees];
                }else{
                }

            }else{
            }

            /*echo 'rrr';
            dump($feetypes);*/
            //货补信息 payee $payees $hbxxs
            $hbxxs='hbxx'.$k;
            $payee=$k;
            if(isset($feetypes[$payee])){
                $num=$feetypes[$payee];
                if(isset($feetype[$num])){
                    $hbv=explode(',',$postData[$hbxxs]);
                    foreach ($hbv as  $hk2=>$hv2){
                        $hbv=explode(':',$hv2);
                        $hbxdata[$hk][$hbv[0]]=$hbv[1];
                       // dump($hbxdata);
                    }

                    /*$postData['hbxx'][$num]=$postData[$hbxxs];
                    $fee['hbxx'][$num]=$postData[$hbxxs];*/
                }else{
                }

            }else{
            }
            // payee   $payees $hbxxs

















            //陈列方式
            $cl_types='cl_type'.$k;
            $cl_type=$k;
            if(isset($feetypes[$cl_type])){

                $num=$feetypes[$cl_type];
                if(isset($feetype[$num])){
                    $postData['cl_type'][$num]=$postData[$cl_types];
                    if(!empty($postData[$cl_types])){
                        $fee['cl_type'][$num]=$postData[$cl_types];
                    }else{
                        $fee['cl_type'][$num]=Null;
                    }
                }
            }
            $cl_places='cl_place'.$k;
            $cl_place=$k;
            if(isset($feetypes[$cl_place])){
                $num=$feetypes[$cl_place];
                if(isset($feetype[$num])){
                    $postData['cl_place'][$num]=$postData[$cl_places];

                    if(!empty($postData[$cl_places])){
                        $fee['cl_place'][$num]=$postData[$cl_places];
                    }else{
                        $fee['cl_place'][$num]=Null;
                    }

                }

            }

            $cl_sizes='cl_size'.$k;
            $cl_size=$k;
            if(isset($feetypes[$cl_size])){
                $num=$feetypes[$cl_size];
                if(isset($feetype[$num])){
                    $postData['cl_size'][$num]=$postData[$cl_sizes];

                    if(!empty($postData[$cl_sizes])){
                        $fee['cl_size'][$num]=$postData[$cl_sizes];
                    }else{
                        $fee['cl_size'][$num]=Null;
                    }

                }
            }


//payee

            //成本中心
            $cbzx='cbzx'.$k;
            $payee=$k;
            if(isset($feetypes[$payee])){
                $num=$feetypes[$payee];
                if(isset($feetype[$num])){
                    //处理成本中心
                    if(isset($postData[$cbzx])&&!empty($postData[$cbzx])){
                    }else{
                        $postData[$cbzx]=$postData['zon'].',100%';
                    }
                    $fcbzx=explode(';',$postData[$cbzx]);
                    $fcb=array();
                    foreach ($fcbzx as $cbk=>$cbv){
                        $fcbzx2=explode(',',$cbv);
                        $fcb[$cbk]=$fcbzx2;
                    }
                    $fee['cbzx'][$num]=$fcb;
                }else{
                }
            }else{
            }

            //货补



        }

        //echo 'hb';die;
        $fee['feetype']=$feetype;
        foreach ($postData['payee'] as $kk=>$vv){
            if (empty($vv)){
                return json_encode(["msg" => "供应商不能为空", "state" => "2"]);
            }elseif($vv<0){
                $postData['payeetype'][$kk]=1;//收款方是经销商
                $postData['payee'][$kk]=$postData['jxs_id'];
            }else{
                $postData['payeetype'][$kk]=2;//收款方是供应商
            }
            /*if($vv<0){
                $postData['payeetype'][$kk]=1;//收款方是经销商
                $postData['payee'][$kk]=$postData['jxs_id'];
            }else{
                $postData['payeetype'][$kk]=2;//收款方是供应商
            }*/
        }
        $fee['payee']=$postData['payee'];//付款方id
        $fee['payeetype']=$postData['payeetype'];//付款方：1是经销商，2是供应商
        //p($postData);
        if($postData['khxqtype']==2){
            $netcount= count($khxq['jxsxt']);
        }elseif ($postData['khxqtype']==3){
            //数据处理
            if ($postData["nets"]) {
                $netsarr = explode(',', $postData["nets"]);
                $netcount=count($netsarr);
            } else {
                return json_encode(["msg" => "网点不能为空", "state" => "2"]);
            }
        }
        //客户 系统
        $feiyongcount = count($fee['feetype']);
        $procount = count($cpxq['ppnum']);
        //数据混编
        //$netcount = count($netsarr);
        //$feiyongcount = count($fids);
        //$procount = count($prosarr);
        $datalist = [];
        $listnum = 0;
        $apply_id = $postData["ti_id"];
        $numnowdet = Db::table("cg_ti_list")->where(["ti_id" => $apply_id])->max("sn");

        $cbzxnum=0;
        for ($k = 0; $k < $feiyongcount; $k++) {
            $cbzxnum += count($fee['cbzx'][$k]);
        }
        if($postData['khxqtype']==2||$postData['khxqtype']==3){
            $tinum=$cbzxnum*$netcount*$procount;
        }elseif($postData['khxqtype']==1){
            $tinum=$cbzxnum*$procount;
        }

        if($postData['khxqtype']==2){ //客户详情是系统时
            for ($i = 0; $i < $netcount; $i++) {
                //$i循环网点
                //$j循环产品
                for ($j = 0; $j < $procount; $j++) {
                    //计算基准销量

                    //$j循环商品
                    for ($k = 0; $k < $feiyongcount; $k++) {
                        $cbcount = count($fee['cbzx'][$k]);
                        for ($l = 0;$l < $cbcount; $l++){   //成本中心
                            $alltouru='';
                            foreach ($fee['fRmb'] as $fk=>$fv){
                                $alltouru+=$fv;
                            }
                            $allcpzb=0;
                            foreach ($cpxq['profit'] as $zbk=>$zbv){
                                $allcpzb=floatval($allcpzb)+floatval($zbv);
                            }
                            $allroi=($postData['yesSales']-$postData['noSales'])/$alltouru*($allcpzb/$procount);
                            $aaa=($postData['yesSales']-$postData['noSales'])/$tinum*$cpxq['profit'][$j]*0.01;
                            $bbb=$fee['fRmb'][$k]*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000/(1+0.06);
                            $roi=$aaa/$bbb;
                            $roi=$roi*100;
                            $roi=round($roi, 2);

                            $hanshui=$fee['fRmb'][$k]*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000;//含税额
                            $yjsjtrfy=$hanshui/(1+0.06);//未税额，未抵扣即也是预计实际投入费用

                            /*$hanshui=$fee['fRmb'][$k]*(1+0.06);
                            $hanshui=$fee['fRmb'][$k]*(1+0.06);*/

                            /*if($yd[$j]["dikou"]){
                                $tmp["yjsjtrfy"]=$tmp["pizhunweishui"] ;
                            }else{
                                $tmp["yjsjtrfy"]= $tmp["pizhunhanshui"];
                            }*/

                            //当时特价补差类
                            if(isset($postData['fylx'])&&$postData['fylx']==4) {
                                $tmp = [
                                    "fylx"=>4,
                                    "fylxs"=>$postData["fylxs"],
                                    "khtype" => 2, //客户详情（经销商，系统，网点）
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "xt_id" => $khxq['jxsxt'][$i],  //系统
                                    "xt_zb" => $khxq['jxsxtzb'][$i],
                                    "net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   含税总额
                                    "amount" => $yjsjtrfy,//费用说明   未税额
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,//预计含税金额
                                    "pizhunhanshui" => $hanshui,//
                                    "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],

                                    "now_price"=>$cpxq['nowprice'][$j],//现价  ppsm
                                    "yuan_price"=>$cpxq['oldprices'][$j],//原价
                                    "zhejia"=>$cpxq['ZheJiaLv'][$j],//折价率
                                    "jizhunboxnum"=>$cpxq['cpnum'][$j],//箱数

                                    "wangdian_yuan" => $cpxq['oldprices2'][$j],  //网点原供货价
                                    "wangdian_price" => $cpxq['nowprice2'][$j],  //网点现供货价
                                    "wangdian_zhejia" => $cpxq['ZheJiaLv2'][$j],   //网点折价率
                                    "lingshou_price" => $cpxq['yls'][$j], //原零售价
                                    "huodong_price" => $cpxq['hdls'][$j],   //活动零售价
                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }else if(isset($postData['fylx'])&&$postData['fylx']==7) {
                                $tmp = [
                                    "fylx"=>7,
                                    "fylxs"=>$postData["fylxs"],
                                    "khtype" => 2, //客户详情（经销商，系统，网点）
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "xt_id" => $khxq['jxsxt'][$i],  //系统
                                    "xt_zb" => $khxq['jxsxtzb'][$i],
                                    "net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   含税总额
                                    "amount" => $yjsjtrfy,//费用说明   未税额
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,//预计含税金额
                                    "pizhunhanshui" => $hanshui,//
                                    "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],

                                    "wangdian_price" => $cpxq['lssghj'][$j], //零售商供货价
                                    "lingshou_price" => $cpxq['mclsj'][$j],   //卖场零售价

                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }else{
                                $tmp = [
                                    "khtype" => 2, //客户详情（经销商，系统，网点）
                                    "fylxs"=>$postData["fylxs"],
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "xt_id" => $khxq['jxsxt'][$i],  //系统
                                    "xt_zb" => $khxq['jxsxtzb'][$i],
                                    "net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   含税总额
                                    "amount" => $yjsjtrfy,//费用说明   未税额
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,//预计含税金额
                                    "pizhunhanshui" => $hanshui,//
                                    "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],
                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }

//p($tmp);
                            $datalist[] = $tmp;
                            $listnum++;
                        }

                    }
                }

            }
        }elseif ($postData['khxqtype']==1){
            //$i循环网点
            //$j循环产品
            for ($j = 0; $j < $procount; $j++) {
                //计算基准销量
                //$j循环商品
                for ($k = 0; $k < $feiyongcount; $k++) {
                    $cbcount = count($fee['cbzx'][$k]);
                    for ($l = 0;$l < $cbcount; $l++){   //成本中心
                        $alltouru='';
                        foreach ($fee['fRmb'] as $fk=>$fv){
                            $alltouru+=$fv;
                        }

                        $allcpzb=0;
                        foreach ($cpxq['profit'] as $zbk=>$zbv){
                            $allcpzb=floatval($allcpzb)+floatval($zbv);
                        }

                        $allroi=($postData['yesSales']-$postData['noSales'])/$alltouru*($allcpzb/$procount);
                        $aaa=($postData['yesSales']-$postData['noSales'])/$tinum*$cpxq['profit'][$j]*0.01;
                        $bbb=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000/(1+0.06);//实际投入 ，未税投入
                        $roi=$aaa/$bbb;
                        $roi=$roi*100;
                        $roi=round($roi, 2);

                        $hanshui=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000;//含税额  没有系统占比
                        $yjsjtrfy=$hanshui/(1+0.06);//未税额，未抵扣即也是预计实际投入费用
                        if(isset($postData['fylx'])&&$postData['fylx']==2) {
                            $tmp = [
                                "fylx"=>2,
                                "fylxs"=>$postData["fylxs"],
                                "khtype" => 1, //客户详情是经销商
                                "cuser" => Session::get("employee_id"),
                                "puser" => Session::get("employee_id"),
                                "ctime" => time(), "ptime" => time(),
                                "sn" => $listnum + 1 + $numnowdet,
                                //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                //"xt_zb" => $khxq['jxsxtzb'][$i],
                                //"net_num" => $khxq['jxsxtwetnum'][$i],
                                "start" => strtotime($postData["s1"]),
                                "end" => strtotime($postData["s2"]),
                                "expCanTime" => strtotime($postData["expCanTime"]),
                                "ysstart" => strtotime($postData["start"]),//预算开始时间
                                "ysend" => strtotime($postData["end"]), //预算结束时间
                                "brief" => $postData["brief"],
                                "ti_id" => $postData["ti_id"],
                                "feetype" => $fee['feetype'][$k], //费用
                                "payee" => $fee['payee'][$k],//jxs_id
                                "payeetype" => $fee['payeetype'][$k],
                                "paymethod" => $fee['status'][$k],//支付方式
                                "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                "amount" => $yjsjtrfy,
                                "pizhunweishui" => $yjsjtrfy,
                                "cl_type" => $fee['cl_type'][$k],
                                "cl_place" => $fee['cl_place'][$k],
                                "cl_size" => $fee['cl_size'][$k],
                                "jxs_id" => $postData["jxs_id"],//产品
                                "brand" => $cpxq['brand'][$j],
                                "category" => $cpxq['category'][$j],
                                "series" => $cpxq['series'][$j],
                                "sku" => $cpxq['sku'][$j],
                                "product" => $cpxq['product'][$j],
                                "hanshui" => $hanshui,//预计含税金额
                                "pizhunhanshui" => $hanshui,
                                "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额
                                "cp_zb" => $cpxq['ppnum'][$j],
                                "cp_sm" => $cpxq['ppsm'][$j],
                                "cp_type" => $cpxq['type'],
                                "now_price"=>$cpxq['nowprice'][$j],//现价  ppsm
                                "yuan_price"=>$cpxq['oldprices'][$j],//原价
                                "zhejia"=>$cpxq['ZheJiaLv'][$j],//折价率
                                "jizhunboxnum"=>$cpxq['cpnum'][$j],//箱数
                                "cb_name" => $fee['cbzx'][$k][$l][0],
                                "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                "yujiroi"=>$roi,
                                "roi"=>$allroi,
                                //"yujifeiyonglv"=>$postData["yjfyl"],
                                "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"]
                                "yujifeiyonglv"=>$fyl,//费用率
                                "yjSalesType"=>$postData["yjSalesType"],
                                "noSales"=>$postData["noSales"],
                                "totalBenchmarkSales"=>$postData["noSales"],
                                "yesSales"=>$postData["yesSales"],
                                "totalExpectedSales"=>$postData["yesSales"],
                                "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                "hx_status" => 3,
                                "productlat" => $cpxq['type']+1,
                                "shuilv"=>6, // 税率默认为6
                            ];

                        }else{
                            $tmp = [
                                "khtype" => 1, //客户详情是经销商
                                "cuser" => Session::get("employee_id"),
                                "puser" => Session::get("employee_id"),
                                "ctime" => time(), "ptime" => time(),
                                "sn" => $listnum + 1 + $numnowdet,
                                //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                //"xt_zb" => $khxq['jxsxtzb'][$i],
                                //"net_num" => $khxq['jxsxtwetnum'][$i],
                                "start" => strtotime($postData["s1"]),
                                "end" => strtotime($postData["s2"]),
                                "expCanTime" => strtotime($postData["expCanTime"]),
                                "ysstart" => strtotime($postData["start"]),//预算开始时间
                                "ysend" => strtotime($postData["end"]), //预算结束时间
                                "brief" => $postData["brief"],
                                "ti_id" => $postData["ti_id"],
                                "feetype" => $fee['feetype'][$k], //费用
                                "payee" => $fee['payee'][$k],//jxs_id
                                "payeetype" => $fee['payeetype'][$k],
                                "paymethod" => $fee['status'][$k],//支付方式
                                "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                "amount" => $yjsjtrfy,
                                "pizhunweishui" => $yjsjtrfy,
                                //$tmp["pizhunweishui"]

                                "cl_type" => $fee['cl_type'][$k],
                                "cl_place" => $fee['cl_place'][$k],
                                "cl_size" => $fee['cl_size'][$k],
                                "jxs_id" => $postData["jxs_id"],//产品
                                "brand" => $cpxq['brand'][$j],
                                "category" => $cpxq['category'][$j],
                                "series" => $cpxq['series'][$j],
                                "sku" => $cpxq['sku'][$j],
                                "product" => $cpxq['product'][$j],
                                "hanshui" => $hanshui,//预计含税金额
                                "pizhunhanshui" => $hanshui,
                                "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                                "cp_zb" => $cpxq['ppnum'][$j],
                                "cp_sm" => $cpxq['ppsm'][$j],
                                "cp_type" => $cpxq['type'],
                                "cb_name" => $fee['cbzx'][$k][$l][0],
                                "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                "yujiroi"=>$roi,
                                "roi"=>$allroi,
                                //"yujifeiyonglv"=>$postData["yjfyl"],
                                "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"]
                                "yujifeiyonglv"=>$fyl,//费用率
                                "yjSalesType"=>$postData["yjSalesType"],
                                "noSales"=>$postData["noSales"],
                                "totalBenchmarkSales"=>$postData["noSales"],
                                "yesSales"=>$postData["yesSales"],
                                "totalExpectedSales"=>$postData["yesSales"],
                                "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                "hx_status" => 3,
                                "productlat" => $cpxq['type']+1,
                                "shuilv"=>6, // 税率默认为6
                            ];
                        }


                        $datalist[] = $tmp;
                        $listnum++;
                    }

                }
            }

        }elseif ($postData['khxqtype']==3){
            for ($i = 0; $i < $netcount; $i++) {
                for ($j = 0; $j < $procount; $j++) {
                    //计算基准销量
                    //$j循环商品
                    for ($k = 0; $k < $feiyongcount; $k++) {
                        $cbcount = count($fee['cbzx'][$k]);
                        for ($l = 0;$l < $cbcount; $l++){   //成本中心
                            $alltouru='';
                            foreach ($fee['fRmb'] as $fk=>$fv){
                                $alltouru+=$fv;
                            }

                            //echo '8';
                            $allcpzb=0;
                            foreach ($cpxq['profit'] as $zbk=>$zbv){
                                $allcpzb=floatval($allcpzb)+floatval($zbv);
                            }

                            $allroi=($postData['yesSales']-$postData['noSales'])/$alltouru*($allcpzb/$procount);
                            $aaa=($postData['yesSales']-$postData['noSales'])/$tinum*$cpxq['profit'][$j]*0.01;
                            $bbb=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000/(1+0.06)/$netcount;

                            $roi=$aaa/$bbb;
                            $roi=$roi*100;
                            $roi=round($roi, 2);
                            //$hanshui=$fee['fRmb'][$k]*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000;//含税额
                            $hanshui=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000/$netcount;//含税额

                            $yjsjtrfy=$hanshui/(1+0.06);//未税额，未抵扣即也是预计实际投入费用
                            //echo 'tt';
                            /*echo $postData['fylx'];
                            p($cpxq);*/
                            if(isset($postData['fylx'])&&$postData['fylx']==4) {
                                $tmp = [
                                    "fylx"=>4,
                                    "fylxs"=>$postData["fylxs"],
                                    "khtype" => 3,
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "net_id" => $netsarr[$i],
                                    //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                    //"xt_zb" => $khxq['jxsxtzb'][$i],
                                    //"net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                    "amount" => $yjsjtrfy,
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,
                                    "pizhunhanshui" => $hanshui,
                                    "yjsjtrfy" => $yjsjtrfy,
                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],

                                    "now_price"=>$cpxq['nowprice'][$j],//现价  ppsm
                                    "yuan_price"=>$cpxq['oldprices'][$j],//原价
                                    "zhejia"=>$cpxq['ZheJiaLv'][$j],//折价率
                                    "jizhunboxnum"=>$cpxq['cpnum'][$j],//箱数
                                    "wangdian_yuan" => $cpxq['oldprices2'][$j],  //网点原供货价
                                    "wangdian_price" => $cpxq['nowprice2'][$j],  //网点现供货价
                                    "wangdian_zhejia" => $cpxq['ZheJiaLv2'][$j],   //网点折价率
                                    "lingshou_price" => $cpxq['yls'][$j], //原零售价
                                    "huodong_price" => $cpxq['hdls'][$j],   //活动零售价

                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"] 预计费用率
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }else if(isset($postData['fylx'])&&$postData['fylx']==7) {
                                $tmp = [
                                    "fylx"=>7,
                                    "fylxs"=>$postData["fylxs"],
                                    "khtype" => 3,
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "net_id" => $netsarr[$i],
                                    //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                    //"xt_zb" => $khxq['jxsxtzb'][$i],
                                    //"net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                    "amount" => $yjsjtrfy,
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,
                                    "pizhunhanshui" => $hanshui,
                                    "yjsjtrfy" => $yjsjtrfy,
                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],
                                    "wangdian_price" => $cpxq['lssghj'][$j], //零售商供货价
                                    "lingshou_price" => $cpxq['mclsj'][$j],   //卖场零售价

                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"] 预计费用率
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }else{
                                $tmp = [
                                    "khtype" => 3,
                                    "cuser" => Session::get("employee_id"),
                                    "puser" => Session::get("employee_id"),
                                    "ctime" => time(), "ptime" => time(),
                                    "sn" => $listnum + 1 + $numnowdet,
                                    "net_id" => $netsarr[$i],
                                    //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                    //"xt_zb" => $khxq['jxsxtzb'][$i],
                                    //"net_num" => $khxq['jxsxtwetnum'][$i],
                                    "start" => strtotime($postData["s1"]),
                                    "end" => strtotime($postData["s2"]),
                                    "expCanTime" => strtotime($postData["expCanTime"]),
                                    "ysstart" => strtotime($postData["start"]),//预算开始时间
                                    "ysend" => strtotime($postData["end"]), //预算结束时间
                                    "brief" => $postData["brief"],
                                    "ti_id" => $postData["ti_id"],
                                    "feetype" => $fee['feetype'][$k], //费用
                                    "payee" => $fee['payee'][$k],//jxs_id
                                    "payeetype" => $fee['payeetype'][$k],
                                    "paymethod" => $fee['status'][$k],//支付方式
                                    "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                    //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                    "amount" => $yjsjtrfy,
                                    "pizhunweishui" => $yjsjtrfy,
                                    "cl_type" => $fee['cl_type'][$k],
                                    "cl_place" => $fee['cl_place'][$k],
                                    "cl_size" => $fee['cl_size'][$k],
                                    "jxs_id" => $postData["jxs_id"],//产品
                                    "brand" => $cpxq['brand'][$j],
                                    "category" => $cpxq['category'][$j],
                                    "series" => $cpxq['series'][$j],
                                    "sku" => $cpxq['sku'][$j],
                                    "product" => $cpxq['product'][$j],
                                    "hanshui" => $hanshui,
                                    "pizhunhanshui" => $hanshui,
                                    "yjsjtrfy" => $yjsjtrfy,
                                    "cp_zb" => $cpxq['ppnum'][$j],
                                    "cp_sm" => $cpxq['ppsm'][$j],
                                    "cp_type" => $cpxq['type'],
                                    "cb_name" => $fee['cbzx'][$k][$l][0],
                                    "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                    "yujiroi"=>$roi,
                                    "roi"=>$allroi,
                                    //"yujifeiyonglv"=>$postData["yjfyl"],
                                    "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"] 预计费用率
                                    "yujifeiyonglv"=>$fyl,//费用率
                                    "yjSalesType"=>$postData["yjSalesType"],
                                    "noSales"=>$postData["noSales"],
                                    "totalBenchmarkSales"=>$postData["noSales"],
                                    "yesSales"=>$postData["yesSales"],
                                    "totalExpectedSales"=>$postData["yesSales"],
                                    "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                    "hx_status" => 3,
                                    "productlat" => $cpxq['type']+1,
                                    "shuilv"=>6, // 税率默认为6
                                ];
                            }


                            $datalist[] = $tmp;
                            $listnum++;
                        }

                    }
                }

            }
        }

//type_id
        Db::startTrans();

        $tisq=Db::table("cg_ti")->where('id',$postData["ti_id"])->value('khtype');
        //p($datalist);
        /*echo 'tisq';
        dump($tisq);die;*/

        try {
            $productlat=$cpxq['type']+1;
            //dump($productlat);die;
            //echo 'ttt33';
            //dump($datalist);die;
            $res1 = Db::table("cg_ti_list")->insertAll($datalist);


        } catch (\Exception $e) {
            return $e->getMessage();die;
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => "2"]);
        }
        /*dump($res1);
        echo 'tisq';
        p($datalist);*/
        $productlat=$cpxq['type']+1;
        $tisq=Db::table("cg_ti")->where('id',$postData["ti_id"])->value('khtype');
        if(empty($tisq)){
            $data2=['id'=>$postData["ti_id"],'productlat'=>$productlat,'khtype'=>$postData['khxqtype']];
        }elseif ($tisq==$postData['khxqtype']){
            $data2=['id'=>$postData["ti_id"],'productlat'=>$productlat];
        }else{
            $data2=['id'=>$postData["ti_id"],'productlat'=>$productlat,'khtype'=>0];
        }

        //$data2=['id'=>$postData["ti_id"],'productlat'=>$productlat];
        $res2=Db::table("cg_ti")->update($data2);


        if ($res1) {

            Db::commit();
            return json_encode(["msg" => "操作已成功", "state" => "1"]);
        } else {
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => "2"]);
        }





    }




    public function updateapply2(){
        header("Content-type:text/html;charset=utf-8");
        $postData = $this->request->post();
        //p($postData);
        $aid=$postData['ti_id'];
        $ctime=$postData['ctime'];

        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->where("ap.id=$aid and apd.ctime=$ctime ")
            ->field(" apd.ctime,ap.id,apd.start,apd.end,apd.brief,apd.cp_type,noSales,yesSales,feiyonglv,roi,expCanTime,start,end,ysstart,ysend")
            ->group('apd.ctime')
            ->find();
       // echo $postData['s1'];
//        $a=$this->checkDateFormat($postData['s1']);
       // print_r($a);die;

        if(isset($postData['expCanTime'])&&$postData['expCanTime']=='NaN-NaN-NaN'){
            return json_encode(["msg" => "核销时间有误", "state" => "2"]);
        }



        if(isset($postData['s1'])&&($postData['s1']=='startvalue'||$postData['s1']=='undefined-undefined-undefined')){
            $postData['s1']=date('Y-m-d',$apply['start']);
            $postData['s2']=date('Y-m-d',$apply['end']);
        }

        if(isset($postData['start'])&&($postData['start']=='startvalue'||$postData['s1']=='undefined-undefined-undefined')){
            $postData['start']=date('Y-m-d',$apply['ysstart']);
            $postData['end']=date('Y-m-d',$apply['ysend']);
        }


        Db::table("cg_ti_list")->where("ti_id in($aid)  and ctime=$ctime")->delete();


//        p($postData);
        $fyl=$postData['yjfyl'];
        //p($postData); //$postData  yjfyl
        $fee=array(); //费用详情 的信息
        $feetype=array();//
        $jxsxt=array();
        $pp=array();
        $pl=array();
        $xl=array();
        $sku=array();
        $dp=array();

        $hbxx=array();
        if(!isset($postData['fRmb'])){
            return json_encode(["msg" => "至少有一条费用明细", "state" => "2"]);
        }

        foreach ($postData as $k=>&$v){
            $hbnum = substr_count($k, 'hbxx');
            if($hbnum){
                if (!$v){
                }else{
                    $hbfh=str_replace("hbxx","","$k");
                    $hbdata=explode(';',$v);
                    foreach ($hbdata as $hk=>$hv){
                        $hbv=explode(',',$hv);
                        foreach ($hbv as  $hk2=>$hv2){
                            $hbv=explode(':',$hv2);
                            $hbxdata[$hk][$hbv[0]]=$hbv[1];
                        }
                    }
                    foreach ($hbxdata as $kk=>&$vv){
                        $vv['ti_id']=$postData['ti_id'];
                        if(isset($vv['wlName'])){
                            $wlName=$vv['wlName'];
                        }
                        $where = "m_type=2 and is_deleted=0 and is_actived=1 ";
                        $data = Db::table('pro_materials t')->field('t.material_name,t.id,unit,factory')->where($where)->select();
                        foreach ($data as $mk=>$mv){
                            if($mv['material_name']==$wlName){
                                $vv['unit']=$mv['unit'];
                                $vv['factory']=$mv['factory'];
                            }
                        }
                    }
                    foreach ($hbxdata as $hbkk=>$hbvv){
                        Db::table('cg_ti_hb')->insert($hbvv);
                    }

                }
                $nums=count($hbxx);
                array_push($hbxx,"$v");
            }
            $number = substr_count($k, 'feetype');
            if($number){
                if (!$v){
                    return json_encode(["msg" => "费用类型不能为空", "state" => "2"]);
                }
                $strings=str_replace("feetype","","$k");
                $nums=count($feetype);
                $feetypes[$strings]=$nums;  //处理其他参数时需要，比如处理收款方, $nums在处理收款方时当键值
                array_push($feetype,"$v");
            }
//客户详情 系统
            $number2 = substr_count($k, 'JinXiaoShangNum');
            if(isset($postData['khxqtype'])&&$postData['khxqtype']==2&&$number2){
                if (!$v){
                    return json_encode(["msg" => "客户详情请正确填写", "state" => "2"]);
                }
                $strings2=str_replace("JinXiaoShangNum","","$k");
                $nums2=count($jxsxt);
                $jxstypes[$strings2]=$nums2;  //处理其他参数时需要，比如处理收款方, $nums在处理收款方时当键值
                array_push($jxsxt,"$v");//系统投放网点数
            }

            //处理产品详情 品牌 品类 系列 SKU 单品
//品牌
            $number3 = substr_count($k, 'proTableInput0');
            if($number3){
                $strings3=str_replace("proTableInput0","","$k");
                $nums3=count($pp);
                $pptypes[$strings3]=$nums3;  //处理其他参数时需要
                array_push($pp,"$v");
            }
//品类
            $number4 = substr_count($k, 'proTableInput1');
            if($number4){
                $strings4=str_replace("proTableInput1","","$k");
                $nums4=count($pl);
                $pltypes[$strings4]=$nums4;  //处理其他参数时需要
                array_push($pl,"$v");
            }
//系列
            $number5 = substr_count($k, 'proTableInput2');
            if($number5){
                $strings5=str_replace("proTableInput2","","$k");
                $nums5=count($xl);
                $xltypes[$strings5]=$nums5;  //处理其他参数时需要
                array_push($xl,"$v");
            }
//SKU
            $number6 = substr_count($k, 'proTableInput3');
            if($number6){
                $strings6=str_replace("proTableInput3","","$k");
                $nums6=count($sku);
                $skutypes[$strings6]=$nums6;  //处理其他参数时需要
                array_push($sku,"$v");
            }
//单品
            $number7 = substr_count($k, 'proTableInput4');
            if($number7){
                $strings7=str_replace("proTableInput4","","$k");
                $nums7=count($dp);
                $dptypes[$strings7]=$nums7;  //处理其他参数时需要
                array_push($dp,"$v");
            }
        }






        $postData['feetype']=$feetype;//费用类型
        $postData['jxsxt']=$jxsxt;//客户详情  系统
        $ppnum=0;
        $plnum=0;
        $xlnum=0;
        $skunum=0;
        $dpnum=0;
        $i=1;
        $j=1;
        $j2=1;
        $j3=1;
        $j4=1;

        if (!empty($pp)){
            $ppnum = count($pp);
            $i=0;
            foreach ($pp as $k=>$v){
                if(!empty($v)){
                    $i++;
                }
            }
        }
        if (!empty($pl)){
            $plnum = count($pl);
            $j=0;
            foreach ($pl as $k=>$v){
                if(!empty($v)){
                    $j++;
                }
            }
        }
        if (!empty($xl)){
            $xlnum = count($xl);
            $j2=0;
            foreach ($xl as $k=>$v){
                if(!empty($v)){
                    $j2++;
                }
            }
        }//$pl
        if (!empty($sku)){
            $skunum = count($sku);
            $j3=0;
            foreach ($sku as $k=>$v){
                if(!empty($v)){
                    $j3++;
                }
            }
        }//$pl
        if (!empty($dp)){
            $dpnum = count($dp);
            $j4=0;
            foreach ($dp as $k=>$v){
                if(!empty($v)){
                    $j4++;
                }
            }
        }
        $postData['jxsxttype']='';
        if($ppnum==$i){
            $postData['jxsxttype']=0;
            $cpxqtype=0;
            //把 品牌 产品数据拿过来
        }elseif($plnum==$j){
            $postData['jxsxttype']=1;
            $cpxqtype=1;
            $pptypes=$pltypes;
            $pp=$pl;
        }elseif($xlnum==$j2){
            $postData['jxsxttype']=2;
            $cpxqtype=2;
            $pptypes=$xltypes;
            $pp=$xl;
        }elseif($skunum==$j3){
            $postData['jxsxttype']=3;
            $cpxqtype=3;
            $pptypes=$skutypes;
            $pp=$sku;
        }elseif($dpnum==$j4){
            $postData['jxsxttype']=4;
            $cpxqtype=4;
            $pptypes=$dptypes;
            $pp=$dp;
        }
        $postData['pp']=$pp;//客户详情  系统
        $postData['cpzb']=array();
        //产品详情  品牌，品类，系列，SKU,单品
        $cpxq['type']=$cpxqtype;

        foreach ($pptypes as $k=>$v){
            $ppnum='proTableInputBl'.$cpxqtype.$k;
            if(isset($pptypes[$k])){ //需要换 （改变）
                $num=$pptypes[$k];
                if(isset($pp[$num])){
                    if($cpxq['type']!=4){
                        $postData['ppnum'][$num]=$postData[$ppnum];
                        $cpxq['ppnum'][$num]=$postData[$ppnum];
                    }else{
                        $postData['ppnum'][$num]=null;
                        $cpxq['ppnum'][$num]=null;
                    }
                }else{
                }
            }else{
            }
            $ppsm='proTableInputSm'.$cpxqtype.$k;
            if(isset($pptypes[$k])){
                $num2=$pptypes[$k];
                if(isset($pp[$num])){
                    $postData['ppsm'][$num2]=$postData[$ppsm];
                    $cpxq['ppsm'][$num2]=$postData[$ppsm];  //客户详情 系统名称
                }else{
                }
            }else{
            }
        }
        $cpxq['name']=$pp;
        if(isset($cpxq['type'])&&$cpxq['type']==4){
            if(isset($cpxq['name'])&&isset($cpxq['ppnum'])){
                $cpnum=count($cpxq['ppnum']);
                foreach ($cpxq['ppnum'] as $ppk=>&$ppv){
                    $ppv=round(100/$cpnum,2);
                }
            }
        }
        //获取毛利率
        switch ($cpxq['type']){
            case 0:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_brands')->where(['id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    //$cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;
                }
                $cpxq['brand']=$cpxq['name'];
                break;
            case 1:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_category')->alias("cat")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    //$cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;
                }
                $cpxq['category']=$cpxq['name'];
                break;
            case 2:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_series')->alias("ser")
                        ->join("pro_category cat","ser.category_id=cat.id")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    //$cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;

                }
                $cpxq['series']=$cpxq['name'];
                break;
            case 3:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_sku')->alias("sku")
                        ->join("pro_series ser","sku.series_id=ser.id")
                        ->join("pro_category cat","ser.category_id=cat.id")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    //$cpxq['sku'][$cpk]=null;
                    $cpxq['product'][$cpk]=null;
                }
                $cpxq['sku']=$cpxq['name'];
                break;
            case 4:
                foreach ($cpxq['name'] as $cpk=>$ckv){
                    $cpprofit=Db::name('pro_products')->alias("pro")
                        ->join("pro_sku sku","pro.sku_id=sku.id")
                        ->join("pro_series ser","sku.series_id=ser.id")
                        ->join("pro_category cat","ser.category_id=cat.id")
                        ->join("pro_brands br","cat.brand_id=br.id")
                        ->where(['cat.id'=>$ckv])->field('profit')->find();
                    $cpxq['profit'][$cpk]=$cpprofit['profit'];
                    $cpxq['brand'][$cpk]=null;
                    $cpxq['category'][$cpk]=null;
                    $cpxq['series'][$cpk]=null;
                    $cpxq['sku'][$cpk]=null;
                    //$cpxq['product'][$cpk]=null;
                }
                $cpxq['product']=$cpxq['name'];
                break;

        }
        //p($cpxq);// 产品详情 type：0品牌，1品类，2.....;ppnum:费用占比，ppsm：产品说明，name产品名称
        //p($ppnums);
        //产品详情
        $postData['jxsxtname']=array();
        $postData['jxsxtnum']=array();
        //p($feetype);费用类型
        if(isset($postData['khxqtype'])&&$postData['khxqtype']==2){
            foreach ($jxstypes as $k=>$v){
                $xtnum='JinXiaoShang'.$k;
                $payee=$k;
                if(isset($jxstypes[$k])){
                    $num=$jxstypes[$k];
                    if(isset($jxsxt[$num])){  //isset($feetype[$num])  $jxsxt
                        // $postData['payee'][$num]=$feetype[$num];
                        $postData['jxsxt'][$num]=$postData[$xtnum];
                        $jxsnum['jxsxt'][$num]=$postData[$xtnum]; //客户详情 系统 网点数
                        $khxq['jxsxt'][$num]=$postData[$xtnum];
                    }else{
                    }

                }else{
                }
                $xtname='JinXiaoShangBl'.$k;
                $payee=$k;
                if(isset($jxstypes[$payee])){
                    $num=$jxstypes[$payee];
                    if(isset($jxsxt[$num])){ //$feetype[$num]
                        $postData['jxsxtname'][$num]=$postData[$xtname];
                        $jxsname['jxsxtzb'][$num]=$postData[$xtname];  //客户详情 系统名称
                        $khxq['jxsxtzb'][$num]=$postData[$xtname];
                    }else{
                    }

                }else{
                }
            }
            $khxq['jxsxtwetnum']=$jxsxt;
            foreach ($jxstypes as $k=>$v){
                $xtnum='JinXiaoShangNum'.$k;
                $payee=$k;
                if(isset($jxstypes[$k])){
                    $num=$jxstypes[$k];
                    if(isset($feetype[$num])){
                        // $postData['payee'][$num]=$feetype[$num];
                        $postData['jxsxtnum'][$num]=$postData[$xtnum];
                        $jxsnum['jxsxtnum'][$num]=$postData[$xtnum]; //客户详情 系统 网点数
                    }else{
                    }

                }else{
                }
//改为占比
                $xtname='JinXiaoShangBl'.$k;
                $payee=$k;
                if(isset($jxstypes[$payee])){
                    $num=$jxstypes[$payee];
                    if(isset($feetype[$num])){
                        // $postData['payee'][$num]=$feetype[$num];
                        $postData['jxsxtzb'][$num]=$postData[$xtname];
                        $jxsname['jxsxtzb'][$num]=$postData[$xtname];  //客户详情 系统名称
                    }else{
                    }

                }else{
                }
            }
        }

        //dump($khxq); //客户详情网点信息
        /*
         * 费用类型处理
        */
        //未税总额
        if(isset($postData['fRmb']) && is_array($postData['fRmb'])){
            foreach ($postData['fRmb'] as $k1=>$v1){
                if (empty($v1)){
                    return json_encode(["msg" => "未税总额不能为空", "state" => "2"]);
                }
            }
        }
        //支付方式
        if(isset($postData['status']) && is_array($postData['status'])){
            foreach ($postData['status'] as $k1=>$v1){
                if (empty($v1)){
                    return json_encode(["msg" => "支付方式不能为空", "state" => "2"]);
                }
            }
        }
        $fee['feetype']=$feetype; //费用类型
        $fee['fRmb']=$postData['fRmb']; //未税总额
        $fee['status']=$postData['status'];//支付方式
        $fee['fbreif']=$postData['fbreif']; //费用说明
        $postData['payee']=array();
        /*echo 'a454e';
        p($feetypes);*/
        //dump($feetypes);
        foreach ($feetypes as $k=>$v){
            //收款方
            $payees='payee'.$k;
            $payee=$k;
            if(isset($feetypes[$payee])){
                $num=$feetypes[$payee];
                if(isset($feetype[$num])){
                    $postData['payee'][$num]=$postData[$payees];
                    $fee['payee'][$num]=$postData[$payees];
                }else{
                }

            }else{
            }


            // 货补信息 payees
            $hbxxs='hbxx'.$k;
            $payee=$k;
            $hbxdata=array();
            if(isset($feetypes[$payee])){
                $num=$feetypes[$payee];
                if(isset($feetype[$num])) {
                    $postData['hbxx'][$num] = $postData[$hbxxs];
                    $fee['hbxx'][$num] = $postData[$hbxxs];
                    try {
                        $hbdata = explode(';', $postData[$hbxxs]);
                        foreach ($hbdata as $hk => $hv) {
                            if(!empty($hv)){
                                $hbv = explode(',', $hv);
                                foreach ($hbv as $hk2 => $hv2) {
                                    $hbv = explode(':', $hv2);
                                    if(isset($hbv[1])){
                                        $hbxdata[$hk][$hbv[0]] = $hbv[1];
                                    }
                                }
                            }
                        }
                        foreach ($hbxdata as $kk2 => &$vv2) {
                            if(isset($fee['feetype'][$v])){
                                $vv2['fylx']=$fee['feetype'][$v];
                            }else{
                                $vv2['fylx']='';
                            }
                            $vv2['fylx']=$fee['feetype'][$v];
                            $vv2['ti_id'] = $postData['ti_id'];
                            if (isset($vv2['wlName'])) {
                                $wlName = $vv2['wlName'];
                            }
                            $where = "m_type=2 and is_deleted=0 and is_actived=1 ";

                            if(isset($vv2['wlyptype'])&&$vv2['wlyptype']==1){ //物料
                                $data = Db::table('pro_materials t')->field('t.material_name,t.id,unit,factory')->where(['material_name'=>$vv2['wlName']])->find();
                                $vv2['unit'] = $data['unit'];
                                $vv2['factory'] = $data['factory'];
                            }else{ //样品
                                $data = Db::table('pro_products')->alias("p")
                                    ->join("pro_price pp", "pp.pid=p.id")
                                    ->field('p.pro_name,pp.factory,p.unit')->where(['p.pro_name'=>$vv2['wlName']])->find();
                                if(!empty($data)){
                                    $vv2['unit'] = $data['unit'];
                                    $vv2['factory'] = $data['factory'];
                                }
                            }
                        } // $kk  $vv


                    } catch (\Exception $e) {
                        return $e->getMessage();die;
                        Db::rollBack();
                        return json_encode(["msg" => "系统繁忙请稍后再试", "state" => "2"]);
                    }

                }else{
                }

            }

            $allhb[$v]=$hbxdata;
            foreach ($hbxdata as $hk=>$hv){
                $allhb2[]=$hv;
            }



            //陈列方式
            $cl_types='cl_type'.$k;
            $cl_type=$k;
            if(isset($feetypes[$cl_type])){

                $num=$feetypes[$cl_type];
                if(isset($feetype[$num])){
                    $postData['cl_type'][$num]=$postData[$cl_types];
                    if(!empty($postData[$cl_types])){
                        $fee['cl_type'][$num]=$postData[$cl_types];
                    }else{
                        //$fee['cl_type'][$num]=null;
                        $fee['cl_type'][$num]=Null;
                    }


                }

            }
//payee
            $cl_places='cl_place'.$k;
            $cl_place=$k;
            if(isset($feetypes[$cl_place])){
                $num=$feetypes[$cl_place];
                if(isset($feetype[$num])){
                    $postData['cl_place'][$num]=$postData[$cl_places];

                    if(!empty($postData[$cl_places])){
                        $fee['cl_place'][$num]=$postData[$cl_places];
                    }else{
                        //$fee['cl_type'][$num]=null;
                        $fee['cl_place'][$num]=Null;
                    }


                }

            }
//payee

            $cl_sizes='cl_size'.$k;
            $cl_size=$k;
            if(isset($feetypes[$cl_size])){
                $num=$feetypes[$cl_size];
                if(isset($feetype[$num])){
                    $postData['cl_size'][$num]=$postData[$cl_sizes];

                    if(!empty($postData[$cl_sizes])){
                        $fee['cl_size'][$num]=$postData[$cl_sizes];
                    }else{
                        //$fee['cl_type'][$num]=null;
                        $fee['cl_size'][$num]=Null;
                    }

                    //$fee['cl_size'][$num]=$postData[$cl_sizes];
                }
            }


//payee

            //成本中心
            $cbzx='cbzx'.$k;
            $payee=$k;
            if(isset($feetypes[$payee])){
                $num=$feetypes[$payee];
                if(isset($feetype[$num])){
                    //处理成本中心
                    if(isset($postData[$cbzx])&&!empty($postData[$cbzx])){

                    }else{
                        //$postData[$cbzx]='测试系统,100%';
                        $postData[$cbzx]=$postData['zon'].',100%';
                    }

                    $fcbzx=explode(';',$postData[$cbzx]);
                    $fcb=array();
                    foreach ($fcbzx as $cbk=>$cbv){
                        $fcbzx2=explode(',',$cbv);
                        $fcb[$cbk]=$fcbzx2;
                    }
                    $fee['cbzx'][$num]=$fcb;
                }else{
                }
            }else{
            }
        }
        //p($fee);
        //dump($fee);
        $fee['feetype']=$feetype;
        foreach ($postData['payee'] as $kk=>$vv){
            if (empty($vv)){
                return json_encode(["msg" => "供应商不能为空", "state" => "2"]);
            }elseif($vv<0){
                $postData['payeetype'][$kk]=1;//收款方是经销商
                $postData['payee'][$kk]=$postData['jxs_id'];
            }else{
                $postData['payeetype'][$kk]=2;//收款方是供应商
            }
            /*if($vv<0){
                $postData['payeetype'][$kk]=1;//收款方是经销商
                $postData['payee'][$kk]=$postData['jxs_id'];
            }else{
                $postData['payeetype'][$kk]=2;//收款方是供应商
            }*/
        }
        $fee['payee']=$postData['payee'];//付款方id
        $fee['payeetype']=$postData['payeetype'];//付款方：1是经销商，2是供应商
        //p($postData);
        if($postData['khxqtype']==2){
            $netcount= count($khxq['jxsxt']);
        }elseif ($postData['khxqtype']==3){
            //数据处理
            if ($postData["nets"]) {
                $netsarr = explode(',', $postData["nets"]);
                $netcount=count($netsarr);
            } else {
                return json_encode(["msg" => "网点不能为空", "state" => "2"]);
            }
        }
        /*echo 'fee';
        p($fee);*/
        //p($postData);
        //客户 系统
        $feiyongcount = count($fee['feetype']);
        $procount = count($cpxq['ppnum']);
        //数据混编
        //$netcount = count($netsarr);
        //$feiyongcount = count($fids);
        //$procount = count($prosarr);
        $datalist = [];
        $listnum = 0;
        $apply_id = $postData["ti_id"];
        $numnowdet = Db::table("cg_ti_list")->where(["ti_id" => $apply_id])->max("sn");

        $cbzxnum=0;
        for ($k = 0; $k < $feiyongcount; $k++) {
            $cbzxnum += count($fee['cbzx'][$k]);
        }
        if($postData['khxqtype']==2||$postData['khxqtype']==3){
            $tinum=$cbzxnum*$netcount*$procount;
        }elseif($postData['khxqtype']==1){
            $tinum=$cbzxnum*$procount;
        }




        if($postData['khxqtype']==2){ //客户详情是系统时
            for ($i = 0; $i < $netcount; $i++) {
                //$i循环网点
                //$j循环产品
                for ($j = 0; $j < $procount; $j++) {
                    //计算基准销量

                    //$j循环商品
                    for ($k = 0; $k < $feiyongcount; $k++) {
                        $cbcount = count($fee['cbzx'][$k]);
                        for ($l = 0;$l < $cbcount; $l++){   //成本中心
                            $alltouru='';
                            foreach ($fee['fRmb'] as $fk=>$fv){
                                $alltouru+=$fv;
                            }

                            //echo '8';
                            $allcpzb=0;
                            foreach ($cpxq['profit'] as $zbk=>$zbv){
                                $allcpzb=floatval($allcpzb)+floatval($zbv);
                            }
                            // echo '7';
                            // echo $postData['yesSales'];die;
                            //echo '('.$postData['yesSales'].'-'.$postData['noSales'].')/'.$alltouru.'*('.$allcpzb.'/'.$procount.')';die;
                            $allroi=($postData['yesSales']-$postData['noSales'])/$alltouru*($allcpzb/$procount);
                            //echo '6';
                            $aaa=($postData['yesSales']-$postData['noSales'])/$tinum*$cpxq['profit'][$j]*0.01;
                            //$bbb=$alltouru*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000/(1+0.06);
                            $bbb=$fee['fRmb'][$k]*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000/(1+0.06);
                            $roi=$aaa/$bbb;
                            $roi=$roi*100;
                            $roi=round($roi, 2);


                            $hanshui=$fee['fRmb'][$k]*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000;//含税额
                            $yjsjtrfy=$hanshui/(1+0.06);//未税额，未抵扣即也是预计实际投入费用

                            /*$hanshui=$fee['fRmb'][$k]*(1+0.06);
                            $hanshui=$fee['fRmb'][$k]*(1+0.06);*/

                            /*if($yd[$j]["dikou"]){
                                $tmp["yjsjtrfy"]=$tmp["pizhunweishui"] ;
                            }else{
                                $tmp["yjsjtrfy"]= $tmp["pizhunhanshui"];
                            }*/
                            $tmp = [
                                "khtype" => 2, //客户详情（经销商，系统，网点）
                                "cuser" => Session::get("employee_id"),
                                "puser" => Session::get("employee_id"),
                                "ctime" => time(), "ptime" => time(),
                                "sn" => $listnum + 1 + $numnowdet,
                                "xt_id" => $khxq['jxsxt'][$i],  //系统
                                "xt_zb" => $khxq['jxsxtzb'][$i],
                                "net_num" => $khxq['jxsxtwetnum'][$i],
                                "start" => strtotime($postData["s1"]),
                                "end" => strtotime($postData["s2"]),
                                "expCanTime" => strtotime($postData["expCanTime"]),
                                "ysstart" => strtotime($postData["start"]),//预算开始时间
                                "ysend" => strtotime($postData["end"]), //预算结束时间
                                "brief" => $postData["brief"],
                                "ti_id" => $postData["ti_id"],
                                "feetype" => $fee['feetype'][$k], //费用
                                "payee" => $fee['payee'][$k],//jxs_id
                                "payeetype" => $fee['payeetype'][$k],
                                "paymethod" => $fee['status'][$k],//支付方式
                                "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                //"amount" => $fee['fRmb'][$k],//费用说明   含税总额
                                "amount" => $yjsjtrfy,//费用说明   未税额
                                "pizhunweishui" => $yjsjtrfy,
                                "cl_type" => $fee['cl_type'][$k],
                                "cl_place" => $fee['cl_place'][$k],
                                "cl_size" => $fee['cl_size'][$k],
                                "jxs_id" => $postData["jxs_id"],//产品
                                "brand" => $cpxq['brand'][$j],
                                "category" => $cpxq['category'][$j],
                                "series" => $cpxq['series'][$j],
                                "sku" => $cpxq['sku'][$j],
                                "product" => $cpxq['product'][$j],
                                "hanshui" => $hanshui,//预计含税金额
                                "pizhunhanshui" => $hanshui,
                                "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                                "cp_zb" => $cpxq['ppnum'][$j],
                                "cp_sm" => $cpxq['ppsm'][$j],
                                "cp_type" => $cpxq['type'],
                                "cb_name" => $fee['cbzx'][$k][$l][0],
                                "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                "yujiroi"=>$roi,
                                "roi"=>$allroi,
                                //"yujifeiyonglv"=>$postData["yjfyl"],
                                "feiyonglv"=>$fyl,
                                "yujifeiyonglv"=>$fyl,//费用率
                                "yjSalesType"=>$postData["yjSalesType"],
                                "noSales"=>$postData["noSales"],
                                "totalBenchmarkSales"=>$postData["noSales"],
                                "yesSales"=>$postData["yesSales"],
                                "totalExpectedSales"=>$postData["yesSales"],
                                "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                "hx_status" => 3,
                                "productlat" => $cpxq['type']+1,
                            ];
                            $datalist[] = $tmp;
                            $listnum++;
                        }

                    }
                }

            }
        }elseif ($postData['khxqtype']==1){  //
            //$i循环网点
            //$j循环产品
            for ($j = 0; $j < $procount; $j++) {
                //计算基准销量

                //$j循环商品
//$k
                for ($k = 0; $k < $feiyongcount; $k++) {
                    $cbcount = count($fee['cbzx'][$k]);
                    for ($l = 0;$l < $cbcount; $l++){   //成本中心
                        $alltouru='';
                        foreach ($fee['fRmb'] as $fk=>$fv){
                            $alltouru+=$fv;
                        }


                        $allcpzb=0;
                        foreach ($cpxq['profit'] as $zbk=>$zbv){
                            $allcpzb=floatval($allcpzb)+floatval($zbv);
                        }

                        $allroi=($postData['yesSales']-$postData['noSales'])/$alltouru*($allcpzb/$procount);
                        //echo $khxq['jxsxtzb'][$i];
                        //$aaa=($postData['yesSales']-$postData['noSales'])/$tinum*$cpxq['profit'][$j]*0.01;
                        $aaa=($postData['yesSales']-$postData['noSales'])/$tinum*$cpxq['profit'][$j]*0.01;
                        $bbb=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000/(1+0.06);//实际投入 ，未税投入
                        $roi=$aaa/$bbb;
                        $roi=$roi*100;
                        $roi=round($roi, 2);

                        //echo $alltouru.'*'.$khxq['jxsxtzb'][$i].'*'.$cpxq['ppnum'][$j].'*'.$fee['cbzx'][$k][$l]['1'].'/1000000*(1+0.06)'.'=';
                        /*$alltouru=$alltouru*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000/(1+0.06);//0.06是税率
                        $roi=($postData['yesSales']-$postData['noSales'])*$cpxq['profit'][$j]*0.01/($alltouru*$tinum);*/
                        /*$hanshui=$fee['fRmb'][$k]*(1+0.06);
                        $hanshui=$fee['fRmb'][$k]*(1+0.06);*/
                        //此处是否报错
                        $hanshui=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000;//含税额  没有系统占比
                        $yjsjtrfy=$hanshui/(1+0.06);//未税额，未抵扣即也是预计实际投入费用

                        $tmp = [
                            "khtype" => 1,
                            "cuser" => Session::get("employee_id"),
                            "puser" => Session::get("employee_id"),
                            "ctime" => time(), "ptime" => time(),
                            "sn" => $listnum + 1 + $numnowdet,
                            //"xt_id" => $khxq['jxsxt'][$i],  //系统
                            //"xt_zb" => $khxq['jxsxtzb'][$i],
                            //"net_num" => $khxq['jxsxtwetnum'][$i],
                            "start" => strtotime($postData["s1"]),
                            "end" => strtotime($postData["s2"]),
                            "expCanTime" => strtotime($postData["expCanTime"]),
                            "ysstart" => strtotime($postData["start"]),//预算开始时间
                            "ysend" => strtotime($postData["end"]), //预算结束时间
                            "brief" => $postData["brief"],
                            "ti_id" => $postData["ti_id"],
                            "feetype" => $fee['feetype'][$k], //费用
                            "payee" => $fee['payee'][$k],//jxs_id
                            "payeetype" => $fee['payeetype'][$k],
                            "paymethod" => $fee['status'][$k],//支付方式
                            "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                            //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                            "amount" => $yjsjtrfy,
                            "pizhunweishui" => $yjsjtrfy,
                            "cl_type" => $fee['cl_type'][$k],
                            "cl_place" => $fee['cl_place'][$k],
                            "cl_size" => $fee['cl_size'][$k],
                            "jxs_id" => $postData["jxs_id"],//产品
                            "brand" => $cpxq['brand'][$j],
                            "category" => $cpxq['category'][$j],
                            "series" => $cpxq['series'][$j],
                            "sku" => $cpxq['sku'][$j],
                            "product" => $cpxq['product'][$j],
                            "hanshui" => $hanshui,//预计含税金额
                            "pizhunhanshui" => $hanshui,
                            "yjsjtrfy" => $yjsjtrfy, //预计实际投入费用,即未税金额

                            "cp_zb" => $cpxq['ppnum'][$j],
                            "cp_sm" => $cpxq['ppsm'][$j],
                            "cp_type" => $cpxq['type'],
                            "cb_name" => $fee['cbzx'][$k][$l][0],
                            "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                            "yujiroi"=>$roi,
                            "roi"=>$allroi,
                            //"yujifeiyonglv"=>$postData["yjfyl"],
                            "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"]
                            "yujifeiyonglv"=>$fyl,//费用率
                            "yjSalesType"=>$postData["yjSalesType"],
                            "noSales"=>$postData["noSales"],
                            "totalBenchmarkSales"=>$postData["noSales"],
                            "yesSales"=>$postData["yesSales"],
                            "totalExpectedSales"=>$postData["yesSales"],
                            "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                            "hx_status" => 3,
                            "productlat" => $cpxq['type']+1,
                        ];
                        $datalist[] = $tmp;
                        $listnum++;
                    }

                }
            }

        }elseif ($postData['khxqtype']==3){
            for ($i = 0; $i < $netcount; $i++) {
                for ($j = 0; $j < $procount; $j++) {
                    //计算基准销量
                    //$j循环商品
                    for ($k = 0; $k < $feiyongcount; $k++) {
                        $cbcount = count($fee['cbzx'][$k]);
                        for ($l = 0;$l < $cbcount; $l++){   //成本中心
                            $alltouru='';
                            foreach ($fee['fRmb'] as $fk=>$fv){
                                $alltouru+=$fv;
                            }

                            //echo '8';
                            $allcpzb=0;
                            foreach ($cpxq['profit'] as $zbk=>$zbv){
                                $allcpzb=floatval($allcpzb)+floatval($zbv);
                            }

                            $allroi=($postData['yesSales']-$postData['noSales'])/$alltouru*($allcpzb/$procount);
                            $aaa=($postData['yesSales']-$postData['noSales'])/$tinum*$cpxq['profit'][$j]*0.01;
                            $bbb=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000/(1+0.06)/$netcount;

                            $roi=$aaa/$bbb;
                            $roi=$roi*100;
                            $roi=round($roi, 2);
                            //$hanshui=$fee['fRmb'][$k]*$khxq['jxsxtzb'][$i]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/1000000;//含税额
                            $hanshui=$fee['fRmb'][$k]*$cpxq['ppnum'][$j]*$fee['cbzx'][$k][$l]['1']/10000/$netcount;//含税额

                            $yjsjtrfy=$hanshui/(1+0.06);//未税额，未抵扣即也是预计实际投入费用
                            //echo 'tt';
                            $tmp = [
                                "khtype" => 3,
                                "cuser" => Session::get("employee_id"),
                                "puser" => Session::get("employee_id"),
                                "ctime" => time(), "ptime" => time(),
                                "sn" => $listnum + 1 + $numnowdet,
                                "net_id" => $netsarr[$i],
                                //"xt_id" => $khxq['jxsxt'][$i],  //系统
                                //"xt_zb" => $khxq['jxsxtzb'][$i],
                                //"net_num" => $khxq['jxsxtwetnum'][$i],
                                "start" => strtotime($postData["s1"]),
                                "end" => strtotime($postData["s2"]),
                                "expCanTime" => strtotime($postData["expCanTime"]),
                                "ysstart" => strtotime($postData["start"]),//预算开始时间
                                "ysend" => strtotime($postData["end"]), //预算结束时间
                                "brief" => $postData["brief"],
                                "ti_id" => $postData["ti_id"],
                                "feetype" => $fee['feetype'][$k], //费用
                                "payee" => $fee['payee'][$k],//jxs_id
                                "payeetype" => $fee['payeetype'][$k],
                                "paymethod" => $fee['status'][$k],//支付方式
                                "feiyongmiaoshu" => $fee['fbreif'][$k],//费用说明
                                //"amount" => $fee['fRmb'][$k],//费用说明   未税总额
                                "amount" => $yjsjtrfy,
                                "pizhunweishui" => $yjsjtrfy,
                                "cl_type" => $fee['cl_type'][$k],
                                "cl_place" => $fee['cl_place'][$k],
                                "cl_size" => $fee['cl_size'][$k],
                                "jxs_id" => $postData["jxs_id"],//产品
                                "brand" => $cpxq['brand'][$j],
                                "category" => $cpxq['category'][$j],
                                "series" => $cpxq['series'][$j],
                                "sku" => $cpxq['sku'][$j],
                                "product" => $cpxq['product'][$j],
                                "hanshui" => $hanshui,
                                "pizhunhanshui" => $hanshui,
                                "yjsjtrfy" => $yjsjtrfy,
                                "cp_zb" => $cpxq['ppnum'][$j],
                                "cp_sm" => $cpxq['ppsm'][$j],
                                "cp_type" => $cpxq['type'],
                                "cb_name" => $fee['cbzx'][$k][$l][0],
                                "cb_zb" => $fee['cbzx'][$k][$l][1],//成本中心
                                "yujiroi"=>$roi,
                                "roi"=>$allroi,
                                //"yujifeiyonglv"=>$postData["yjfyl"],
                                "feiyonglv"=>$fyl,//$fyl=$postData["yjfyl"] 预计费用率
                                "yujifeiyonglv"=>$fyl,//费用率
                                "yjSalesType"=>$postData["yjSalesType"],
                                "noSales"=>$postData["noSales"],
                                "totalBenchmarkSales"=>$postData["noSales"],
                                "yesSales"=>$postData["yesSales"],
                                "totalExpectedSales"=>$postData["yesSales"],
                                "is_shejixiaoliang"=>$postData["is_shejixiaoliang"],
                                "hx_status" => 3,
                                "productlat" => $cpxq['type']+1,
                            ];
                            $datalist[] = $tmp;
                            $listnum++;
                        }

                    }
                }

            }
        }

//type_id

        Db::startTrans();

        $tisq=Db::table("cg_ti")->where('id',$postData["ti_id"])->value('khtype');
        /*echo 'tisq';
        dump($tisq);*/

        try {
            $productlat=$cpxq['type']+1;
            //dump($productlat);die;
            //echo 'ttt33';
            //dump($datalist);die;
            $res1 = Db::table("cg_ti_list")->insertAll($datalist);


        } catch (\Exception $e) {
            //return $e->getMessage();
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => "2"]);
        }
        $productlat=$cpxq['type']+1;
        $tisq=Db::table("cg_ti")->where('id',$postData["ti_id"])->value('khtype');
        if(empty($tisq)){
            $data2=['id'=>$postData["ti_id"],'productlat'=>$productlat,'khtype'=>$postData['khxqtype']];
        }elseif ($tisq==$postData['khxqtype']){
            $data2=['id'=>$postData["ti_id"],'productlat'=>$productlat];
        }else{
            $data2=['id'=>$postData["ti_id"],'productlat'=>$productlat,'khtype'=>0];
        }

        //$data2=['id'=>$postData["ti_id"],'productlat'=>$productlat];
        $res2=Db::table("cg_ti")->update($data2);


        if ($res1) {

            Db::commit();
            return json_encode(["msg" => "操作已成功", "state" => "1"]);
        } else {
            Db::rollBack();
            return json_encode(["msg" => "系统繁忙请稍后再试", "state" => "2"]);
        }

    }


    //根据id查找产品纬度值
    public function productlatval($v){
        if($v['brand']){
            return db('pro_brands')->where('id',$v['brand'])->value('brand_name');
        }elseif($v['category']){
            return db('pro_category')->where('id',$v['category'])->value('category_name');
        }elseif($v['series']){
            return db('pro_series')->where('id',$v['series'])->value('series_name');
        }elseif($v['sku']){
            return db('pro_sku')->where('id',$v['sku'])->value('sku_name');
        }elseif($v['product']){
            return db('pro_products')->where('id',$v['product'])->value('pro_name');
        }
    }


}